zoukankan      html  css  js  c++  java
  • 代码实现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

  • 相关阅读:
    Ranorex发布2.3版本支持Flex4
    TestComplete基础教程
    2009年缺陷跟踪和测试管理工具使用情况调查报告
    软件自动化测试资源列表
    TestComplete资源列表
    分治算法
    画表格蓝桥杯
    分红酒蓝桥杯
    “硬币方案”蓝桥杯
    微生物增值蓝桥杯
  • 原文地址:https://www.cnblogs.com/wangqc/p/sqlAppend.html
Copyright © 2011-2022 走看看