附加数据库函数

本文介绍了一个使用C#程序来启动SQL服务并创建数据库的过程。通过执行系统命令启动SQL服务,然后利用SqlConnection连接到SQL Server,执行SQL命令以附加现有的NORTHWND数据库。

  private void CreateDataBase()
        {
            // 启动SQL服务, 预防装完之后服务未启动
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;

            p.Start();
            p.StandardInput.WriteLine("net start MSSQL$HW1000");
            p.StandardInput.WriteLine("exit");
            p.StandardOutput.ReadToEnd();

            string strSql = string.Format("server={0}; user id={1}; password={2}; Database=master", "(local)\\SQLEXPRESS", "sa", "sasasa");

           //string strSql = string.Format("Data Source=(local)\\SQLEXPRESS; Initial Catalog=master;Integrated Security=SSPI;");           

            string strMdf = "C:\\新建文件夹http://www.cnblogs.com/lbg280/admin/file://northwnd.mdf/";
            string strLdf = "C:\\新建文件夹http://www.cnblogs.com/lbg280/admin/file://northwnd.ldf/";
            //LogWriter.LogEvent("MDF路径:" + strMdf);                      
            string str;
            SqlConnection myConn = new SqlConnection(strSql);
            str = "EXEC sp_attach_db @dbname = N'NORTHWND', @filename1 = N'" + strMdf + "',@filename2=N'" + strLdf + "'";
            SqlCommand myCommand = new SqlCommand(str, myConn);
            myConn.Open();
            myCommand.ExecuteNonQuery();
            myConn.Close();
        }

转载于:https://www.cnblogs.com/lbg280/archive/2010/04/10/1709182.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值