2013-03-13 59 views
-1

我有很多的錯誤不能打開連接等等。我使用VS 2010的C#WPF創建在C#WPF運行時錯誤的SQL Server DB

String str; 
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master"); 

str = " CREATE DATABASE " 
    + " ON PRIMARY " 
    + " (NAME = " + "MyDatabase_Data" + ", " 
    + " FILENAME = '" + "C:\\MyDatabaseData.mdf" + "', " 
    + " SIZE = 2MB," 
    + " FILEGROWTH =" + "10%" + ") " 
    + " LOG ON (NAME =" + "MyDatabase_Log" + ", " 
    + " FILENAME = '" + "C:\\MyDatabaseLog.ldf" + "', " 
    + " SIZE = 1MB, " 
    + " FILEGROWTH =" + "10%" + ") "; 

SqlCommand myCommand = new SqlCommand(str, myConn); 
try 
{ 
    myConn.Open(); 
    myCommand.ExecuteNonQuery(); 
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information); 
} 
catch (System.Exception ex) 
{ 
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information); 
} 
finally 
{ 
    if (myConn.State == ConnectionState.Open) 
    { 
     myConn.Close(); 
    } 
} 
+1

你準確得到了哪些錯誤? – Mat 2013-03-13 10:21:39

回答

0

添加以下引用:

  • c:\ Program Files \ Microsoft SQL
    Server \ 100 \ SDK \ Assemblies \ Microsoft.SqlServer.Smo.dll
  • C:\ Program Files(x86)\ Microsoft SQL Server \ 100 \ SDK \ Assemblies \ Microsoft。 SqlServer.Management.Sdk.Sfc.dll
  • C:\ Program Files文件\微軟SQL服務器 \ 100 \ SDK \組件\ Microsoft.SqlServer.ConnectionInfo.dll

在應用程序配置請inser下面的代碼片段

<startup useLegacyV2RuntimeActivationPolicy="true"> 
    <supportedRuntime version="v4.0"/> 
</startup> 

的代碼:

var myConn = "Server=localhost;Integrated security=SSPI;database=master"; 

//The CREATE DATABASE statement failed. The primary file must be at least 3 MB to accommodate a copy of the model database. 
var command = @" 
CREATE DATABASE myDB 
ON PRIMARY 
(
NAME = MyDatabaseData, 
FILENAME = 'C:\Temp\MyDatabaseData.mdf', 
SIZE = 3MB, 
FILEGROWTH =10% 
) 
LOG ON 
(
NAME =MyDatabaseLog, 
FILENAME = 'C:\Temp\MyDatabaseLog.ldf', 
SIZE = 1MB, 
FILEGROWTH =10% 
)"; 

using (var conn = new SqlConnection(myConn)) 
{ 
    try 
    { 
    var server = new Server(new ServerConnection(conn)); 
    server.ConnectionContext.ExecuteNonQuery(command); 
    } 
    catch (Exception e) 
    { 
    Console.WriteLine(e.Message); 

    } 
}