• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
HS.H °
财富来源于拼搏, 命运取决与奋斗!
博客园    首页    新随笔    联系   管理    订阅  订阅

代码实现sql数据库的附加(通常在安装的时候)

判断数据库是否已经存在
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();


作者:wangqc
出处:http://www.cnblogs.com/wangqc/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-wangqc。

posted @ 2013-08-10 10:08  没有终点的列车  阅读(325)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3