判断数据库是否已经存在
SqlConnection judgeConn = new SqlConnection("server=.;database=master;uid="+username+";pwd="+userpwd+";");
judgeConn.Open();
SqlCommand command = new SqlCommand("select count(*) from sys.databases where name='"+dbname+"'",judgeConn);
int dbCount = Convert.ToInt32(command.ExecuteScalar());
if(dbCount > 0)
{
//删除数据库
string dropDbName = "Drop database "+dbname;
SqlCommand dropDbCommand = new SqlCommand(dropDbName,judgeConn);
dropDbCommand.ExecuteNonQuery();
}
judgeConn.Close();
附加数据库
public bool ExcuteSqlFiles(string softFileListPath,SqlConnection conn)
{
try
{
string []sqlFiles = Directory.GetFileSystemEntries(softFileListPath);
//假设目录下的都是文件夹
foreach(string file in sqlFiles)
{
if(Directory.Exists(file))
{
ExcuteSqlFiles(file,conn);
}
else
{
FileStream stream = new FileStream(file,FileMode.Open);
StreamReader sr = new StreamReader(stream,System.Text.Encoding.Default);
string sql = sr.ReadToEnd();
SqlCommand command = new SqlCommand(sql,conn);
try
{
executeResult = command.ExecuteNonQuery();
}
catch(Exception ex2)
{
MessageBox.Show(file+" sql文件执行失败! 原因: "+ex2.Message);
return false;
}
}
}
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source="+server+";AttachDbFilename="+dbpath+";database="+dbname+";uid="+username+";pwd="+userpwd+"";
conn.Open(); //附加成功
//执行sql文件
if(!ExcuteSqlFiles(softFileListPath,conn))
{
nextFlag = false;
}
conn.Close();