C# 建数sqlserver据库程序 用winform运行SQL脚本创建数据库

需要用到2个引用:

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

路径大概是:C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies

只要安装了SQL2008就行,具体百度。

http://download.csdn.net/download/qq_24554581/10040426

如果实在找不着,又没积分下载的话,用ADO.NET分段吧...

这是直接把sql脚本的语句挂到数据库中运行,ADO.NET有很多限制,又因为数据库导出的脚本又基本中枪,所以只能乳此了。

首先,界面长这样:

弄成这样不难...随便搞搞就行...就不放代码了。

时间是为了提示用户程序没挂掉,别乱点。。。

构建数据库语句,目标字符串:

这是手动拼接的


CREATE DATABASE 数据库名
ON
(
    NAME = '数据库名_data',
    FILENAME = 'D:\SQL\数据库名_data.mdf',
    SIZE = 5MB,
    MAXSIZE=5,
    FILEGROWTH = 20
)
LOG ON
(
    NAME = '数据库名_log',
    FILENAME = 'D:\SQL\数据库名_log.ldf',
    SIZE = 2MB,
    MAXSIZE=20,
    FILEGROWTH = 1MB
);
 

注意事项:
眼号啊,逗号啊,括号啊全都不能省

直接上代码:

注释已经说的很明白了,就不罗嗦了,按照代码调整好界面控件的name属性就能用了,

   ManualResetEvent ManualEvent;
        public string _SqlFile = Directory.GetCurrentDirectory();//获取应用程序的当前工作目录
        public MainForm()
        {
            InitializeComponent();
 
            //初始化界面
            try
            {
                if (string.IsNullOrWhiteSpace(DbHelp.ConnStr))
                {
                    MessageShow("未找到数据库连接字符串", "初始化出错", MessageBoxIcon.Question);
                    return;
                }
                String[] config = DbHelp.ConnStr.Split(';');
                Service.Text = config[0].Split('=')[1];
                DbName.Text = config[1].Split('=')[1];
                UserName.Text = config[2].Split('=')[1];
                Password.Text = config[3].Split('=')[1];
            }
            catch (Exception ex)
            {
                MessageShow(ex.Message, "获取配置数据失败", MessageBoxIcon.Stop);
                return;
            }
        }
 
        /// <summary>
        /// 安装库
        /// </summary>
        private void CreateDbBtn_Click(object sender, EventArgs e)
        {
            IsEnabled(false);
            ManualEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(ThreadCreate, ManualEvent);//由线程池管理
            msg.Visible = true;
            ManualEvent.WaitOne();//无限等待
            msg.Visible = false;
            ManualEvent = null;
            //IsEnabled(true);
        }
 
        /// <summary>
        /// 安装库线程
        /// </summary>
        private void ThreadCreate(object objEvent)
        {
            string masterstr = GetConnStr();//连接字符串
            if (string.IsNullOrWhiteSpace(masterstr))//判空
            {
                MessageShow("请填完整", "创建失败", MessageBoxIcon.Information);
                return;
            }
            try
            {
                #region 检查数据
                if (!TestConnDb(masterstr))//判断
                {
                    MessageShow("数据库已存在", "创建失败", MessageBoxIcon.Warning);
                    return;
                }
                DirectoryInfo folder = new DirectoryInfo(_SqlFile);
                FileInfo[] fileInfos = folder.GetFiles("*.sql");//检索所有文件
                if (fileInfos.Length != 1)//脚本判断
                {
                    MessageShow("未找到或有多个数据库脚本", "创建失败", MessageBoxIcon.Warning);
                    return;
                }
                string Sqlpath = _SqlFile + @"\" + fileInfos[0].Name;//脚本物理路径
                string dbname = DbName.Text.Trim();//数据库名
                string sqlcon = masterstr.Replace(";database=master;", ";database=" + dbname + ";");//连接字符串
                string dbpath = DbPath.Text.Trim();//安装路径
                string sqlstr = SQLCreate(Sqlpath);//读取数据库脚本语句
                if (string.IsNullOrWhiteSpace(sqlstr))
                    return;
                #endregion
 
                #region 创建
                StringBuilder sb = new StringBuilder();//创建库脚本
                sb.Append("CREATE DATABASE " + dbname + @" ON ");
                sb.Append("(NAME='" + dbname + @"_data',FILENAME='" + dbpath + @"\" + dbname);
                sb.Append(@"_data.mdf',size=3," + @"FILEGROWTH = 10%)");
                sb.Append(@"LOG ON(NAME='" + dbname + @"_log',FILENAME='" + dbpath + @"\" + dbname);
                sb.Append(@"_log.ldf',size=3," + @"FILEGROWTH = 10%);");
                if (!Directory.Exists(dbpath))//创建文件夹
                {
                    Directory.CreateDirectory(dbpath);
                }
                DbHelp.ExecNonQuery(sb.ToString(), masterstr);//创建库
                DbHelp.SqlServer(sqlstr, sqlcon);//运行库脚本
                //DbHelp.ExecNonQuery(sqlstr, sqlcon);
                #endregion
                //UpAppconfig("ConnectionString", sqlcon);
                //UpWebconfig("ConnectionString", sqlcon);
                MessageShow("创建成功", "创建数据库", MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                LogFile(ex.Message);
                MessageShow(ex.Message, "创建失败", MessageBoxIcon.Error);
            }
            finally
            {
                ((ManualResetEvent)objEvent).Set();//线程结束
            }
        }
 
        /// <summary>
        /// 拼接数据库语句
        /// </summary>
        private string SQLCreate(string Sqlpath)
        {
            try
            {
                string sqlstr = string.Empty;
                using (FileStream fsr = new FileStream(Sqlpath, FileMode.Open, FileAccess.Read))//读
                {
                    StreamReader sr = new StreamReader(fsr, Encoding.Default);
                    sqlstr = sr.ReadToEnd();//将脚本原有数据全部读出
                    sr.Close();
                }
                //判断
                CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
                int cnum = Compare.IndexOf(sqlstr, "CREATE DATABASE ", CompareOptions.IgnoreCase);
                if (cnum >= 0)
                {
                    MessageShow("请先把脚本中的创建和USE GO语句删除", "数据库脚本异常", MessageBoxIcon.Warning);
                    return "";
                }
                return sqlstr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 测试连接
        /// </summary>
        private void TestDbBtn_Click(object sender, EventArgs e)
        {
            IsEnabled(false);
            ManualEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(ThreadTest, ManualEvent);//由线程池管理
            msg.Visible = true;
            ManualEvent.WaitOne();//无限等待
            msg.Visible = false;
            ManualEvent = null;
            //IsEnabled(true);
        }
 
        /// <summary>
        /// 测试连接线程
        /// </summary>
        private void ThreadTest(object objEvent)
        {
            string connstr = GetConnStr();
            try
            {
                if (!string.IsNullOrWhiteSpace(connstr))
                {
                    if (TestConnDb(connstr))
                    {
                        MessageShow("可以开始创建数据库", "测试成功", MessageBoxIcon.Asterisk);
                    }
                    else
                        MessageShow("数据库重名", "测试失败", MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageShow(ex.Message, "获取数据库实例失败", MessageBoxIcon.Error);
            }
            finally
            {
                ((ManualResetEvent)objEvent).Set();//线程结束
            }
        }
 
        /// <summary>
        /// 判断是否能连接数据库和重名
        /// </summary>
        private bool TestConnDb(string connstr)
        {
            try
            {
                StringBuilder DBlist = new StringBuilder();
                DataTable dt = DbHelp.Query("select name from master..sysdatabases", connstr).Tables[0];//获取所有库
                foreach (DataRow row in dt.Rows)
                {
                    DBlist.Append(row["name"].ToString() + "\r\n");
                }
                string dbname = DbName.Text.Trim();
                if (DBlist.ToString().IndexOf(dbname) <= 0 && !(dbname.Equals("master", StringComparison.OrdinalIgnoreCase)))//重名判断
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        private string GetConnStr()
        {
            string service = Service.Text.Trim();
            string dabane = DbName.Text.Trim();
            string username = UserName.Text.Trim();
            string password = Password.Text.Trim();
            if (string.IsNullOrWhiteSpace(service) || string.IsNullOrWhiteSpace(dabane)
              || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                MessageShow("请将信息填完整", "操作停止", MessageBoxIcon.Warning);
                return "";
            }
            return "server=" + service + ";database=master;uid=" + username + ";pwd=" + password;
        }
 
        /// <summary>
        /// 是否能操作控件
        /// </summary>
        private void IsEnabled(bool istrue)
        {
            if (istrue)
            {
                Invoke((Action)(() =>
                {
                    //Enabled = true;
                    TestDbBtn.Enabled = true;
                    CreateDbBtn.Enabled = true;
                    DbPath.Enabled = true;
                    UserName.Enabled = true;
                    Service.Enabled = true;
                    Password.Enabled = true;
                    DbName.Enabled = true;
                    DbPath.Enabled = true;
                    PathBtn.Enabled = true;
                }));
            }
            else
            {
                Invoke((Action)(() =>
                {
                    //Enabled = false;
                    TestDbBtn.Enabled = false;
                    CreateDbBtn.Enabled = false;
                    DbPath.Enabled = false;
                    UserName.Enabled = false;
                    Service.Enabled = false;
                    Password.Enabled = false;
                    DbName.Enabled = false;
                    DbPath.Enabled = false;
                    PathBtn.Enabled = false;
                }));
            }
        }
 
        /// <summary>
        /// 日志文件
        /// </summary>
        public void LogFile(string Error)
        {
            string logfile = Application.StartupPath + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + " Log.txt";
            try
            {
                if (File.Exists(logfile))
                {
                    FileStream fs = new FileStream(logfile, FileMode.Open, FileAccess.Write);//存在
                    StreamWriter sw = new StreamWriter(fs);
                    long fl = fs.Length;//获取文本字符长度
                    fs.Seek(fl, SeekOrigin.Begin);//定位开始位置
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + Error);//开始写入值
                    sw.Close();
                    fs.Close();
                }
                else
                {
                    FileStream fs = new FileStream(logfile, FileMode.Create, FileAccess.Write);//不存在
                    StreamWriter sw = new StreamWriter(fs);
                    long fl = fs.Length;//获取文本字符长度
                    fs.Seek(fl, SeekOrigin.End);//定位末尾位置
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + Error);//开始写入值
                    sw.Close();
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 选择数据库安装路径
        /// </summary>
        private void PathBtn_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            if (path.SelectedPath.Trim() == "")
                return;
            DbPath.Text = path.SelectedPath;
        }
 
        /// <summary>
        /// 弹窗提示
        /// </summary>
        private void MessageShow(string msg, string title, MessageBoxIcon boxIcon)
        {
            //为防阻塞,多线程弹出提示框
            new Thread(() => { MessageBox.Show(msg, title, MessageBoxButtons.OK, boxIcon); IsEnabled(true); }).Start();
            //MessageBox.Show(msg, title, MessageBoxButtons.OK, boxIcon);
        }
 
        /// <summary>
        /// 时间
        /// </summary>
        private void TipTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            
            TimeLabel.Text= DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            TimeLabel.Update();
        }
 

数据库操作代码:

用了个静态类来放

  public static string ConnStr = ConfigurationManager.AppSettings["ConnectionString"];
 
        /// <summary>
        /// 执行一条SQL语句,返回影响行数,可选库
        /// </summary>
        public static int ExecNonQuery(string strSql, string con)
        {
            try
            {
                int iResult = 0;
                using (SqlConnection cn = new SqlConnection(con))
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    sqlCmd.Connection = cn;
                    sqlCmd.CommandTimeout = 300;
                    sqlCmd.CommandText = strSql;
                    cn.Open();
                    iResult = sqlCmd.ExecuteNonQuery();
                }
                return iResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, string Conn)
        {
            using (SqlConnection connection = new SqlConnection(Conn))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds);
                    return ds;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
 
        /// <summary>
        /// 运行sql脚本文件
        /// </summary>
        public static void SqlServer(string sqlstr, string con)
        {
            try
            {
                SqlConnection sqlcon = new SqlConnection(con);
                Server server = new Server(new ServerConnection(sqlcon));
                server.ConnectionContext.ExecuteNonQuery(sqlstr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
 
        }
 

 

可以加上进度条,我做的进度条是个水货,没监听线程进行情况,就自个在那跑,

99%卡住后等待运行完关掉,就不贴出来了。。。

end.

————————————————
版权声明:本文为CSDN博主「浮光-掠影」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_24554581/article/details/78352728

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页

打赏作者

匿名劉

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值