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

  • 相关阅读:
    upc组队赛1 黑暗意志【stl-map】
    upc组队赛1 闪闪发光 【优先队列】
    upc组队赛1 流连人间的苏苏
    POJ 2387 Til the Cows Come Home 【最短路SPFA】
    POJ 2421 Constructing Roads 【最小生成树Kruscal】
    qrcode-使用
    submlie 配置php运行
    composer 安装laravel
    composer 配置镜像
    Laravel-队列
  • 原文地址:https://www.cnblogs.com/wangqc/p/sqlAppend.html
Copyright © 2011-2022 走看看