2016-09-14 58 views
-1

我想創建一個數據庫,如果它不存在。我想這個代碼做到這一點,但它有錯誤,我得到這個消息如何創建數據庫,如果不存在於C#Winforms

enter image description here

請幫助。

代碼:

if(dbex == false) 
{ 
    string str; 

    SqlConnection mycon = new SqlConnection("Server=.\\sqlexpress;initial catalog=Masalehforoshi;Integrated security=SSPI;database=master"); 
    str = "CREATE DATABASE [Masalehforoshi] CONTAINMENT = NONE ON PRIMARY" + 
       "(NAME=N'Masalehforoshi'," + 
       @"FILENAME=N'C:\data\Masalehforoshi.mdf' " + 
       ",SIZE=3072KB,MAXSIZE=UNLIMITED,FILEGROWTH=1024KB)" + 
       "LOG ON (NAME=N'Masalehforoshi_log.', " + 
       @"FILENAME=N'C:\Masalehforoshi_log.ldf' "+ 
       ",SIZE=1024KB,MAXSIZE=2048GB,FILEGROWTH=10%)"; 

    SqlCommand mycommand = new SqlCommand(str, mycon); 

    try 
    { 
     mycommand.Connection.Open(); 
     mycommand.ExecuteNonQuery(); 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show(ex.ToString(), "myprogram", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
    } 
    finally 
    { 
     if(mycon.State == ConnectionState.Open) 
     { 
      mycon.Close(); 
     } 
    } 
} 
+1

功能什麼的SQL Server Express版本是你使用? – Steve

+0

它看起來像是一個sql異常。如果我是你,我會在[SQL Server Management Studio](https://msdn.microsoft.com/en-us/library/mt238290.aspx)中調試你的查詢。 –

回答

0

基於具有類似的數據庫創建腳本,我建議去掉「遏制= NONE」部分支持文章https://support.microsoft.com/en-us/kb/307283上。

默認情況下,所有的SQL Server 2012及更高版本數據庫有一個遏制設置爲none(https://msdn.microsoft.com/en-us/library/ff929071.aspx),所以它可能是沒有必要爲你的腳本

這可能是結結實實.NET不支持那tsql命令,有一整個其他SQL Server管理對象庫可用於與高級數據庫和綱要腳本https://msdn.microsoft.com/en-us/library/ms162169.aspx混淆。我使用它在應用程序啓動過程中用表格定義等來創建丟失的數據庫。

1

我創建數據庫功能

public bool CreateDatabase(SqlConnection connection, string txtDatabase) 
{ 
    String CreateDatabase; 
    string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
    GrantAccess(appPath); //Need to assign the permission for current application to allow create database on server (if you are in domain). 
    bool IsExits = CheckDatabaseExists(connection, txtDatabase); //Check database exists in sql server. 
    if (!IsExits) 
    { 
     CreateDatabase = "CREATE DATABASE " + txtDatabase + " ; "; 
     SqlCommand command = new SqlCommand(CreateDatabase, connection); 
     try 
     { 
      connection.Open(); 
      command.ExecuteNonQuery(); 
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show("Please Check Server and Database name.Server and Database name are incorrect .", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); 
      return false; 
     } 
     finally 
     { 
      if (connection.State == ConnectionState.Open) 
      { 
       connection.Close(); 
      } 
     } 
     return true; 
    } 
} 

我多個GrantAccess功能您允許電流應用

public static bool GrantAccess(string fullPath) 
{ 
    DirectoryInfo info = new DirectoryInfo(fullPath); 
    WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent(); 
    DirectorySecurity ds = info.GetAccessControl(); 
    ds.AddAccessRule(new FileSystemAccessRule(self.Name, 
    FileSystemRights.FullControl, 
    InheritanceFlags.ObjectInherit | 
    InheritanceFlags.ContainerInherit, 
    PropagationFlags.None, 
    AccessControlType.Allow)); 
    info.SetAccessControl(ds); 
    return true; 
} 

檢查數據庫中存在以下

public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName) 
{ 
    string sqlCreateDBQuery; 
    bool result = false; 

    try 
    { 
     sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName); 
     using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn)) 
     { 
      tmpConn.Open(); 
      object resultObj = sqlCmd.ExecuteScalar(); 
      int databaseID = 0; 
      if (resultObj != null) 
      { 
       int.TryParse(resultObj.ToString(), out databaseID); 
      } 
      tmpConn.Close(); 
      result = (databaseID > 0); 
     } 
    } 
    catch (Exception) 
    { 
     result = false; 
    } 
    return result; 
} 
相關問題