日期:2014-05-20  浏览次数:20877 次

我想写一个创建数据库的语句在C#里怎么写?
SqlConnection   conn   =   new   SqlConnection( "Data   Source=(local);initial   catalog=master;user   id=sa;pwd= ");
                        SqlCommand   command   =   new   SqlCommand( "create   database   ' "   +   DataBaseName   +   " ' ",   conn);
                        try  
                        {
                                conn.Open();
                                command.ExecuteNonQuery();
                       
                        }
                        catch   (Exception   ex)
                        {
                                throw   new   Exception(ex.Message);

                        }
                        finally
                        {
                                conn.Close();

                        }
  总是报错!可能command.ExecuteNonQuery();的原因

------解决方案--------------------
public bool CreatDatabase(string DatabaseName,string DataFile,string LogFile)
{
string str;
SqlConnection myConn = new SqlConnection ( "Server=localhost;Integrated security=SSPI;database=master ");

str = "CREATE DATABASE "+ DatabaseName + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = ' " + DataFile + " ', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = ' " + LogFile + " ', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%) ";

SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show( "DataBase is Created Successfully ", "MyProgram ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
------解决方案--------------------
不要加引号