我连接到数据库(sql server 2000)之前,总要在sql server 2000的企业管理器中先手动的通过"数据库"--"所有任务"--"附加数据库"来把自己数据库的MDF文件添加进来.
程序中使用的是简单的数据库连接字符串(数据源是本地,登陆类型为本地windows验证,数据库名为MYDB).
sql server 2000安装时选的是windows验证.我想在程序中完成"数据库"--"所有任务"--"附加数据库"来把自己数据库的MDF文件添加进来.这个动作,请问如何写代码实现啊?

解决方案 »

  1.   

    我的意思是说,我把程序给别人不可能叫人家自己先sql server 2000的企业管理器中先手动的通过"数据库"--"所有任务"--"附加数据库"来把自己数据库的MDF文件添加进来以后再运行程序吧
      

  2.   

    用备份+恢复 ,sql语句就可以做到。
      

  3.   

    EXEC sp_attach_db 'DatabaseName','D:\YourPath\database_data.mdf','D:\YourPath\database_log.ldf'
      

  4.   

    我是这样写的,可是sqlspcom.ExecuteNonQuery();报异常说必须要有两个参数,可我查MSDN这个函数没参数啊.            FileStream fileConnection;
                string @strsp_attach_db;            //sp_attach_db.ini内容:
                //Data Source = (local);
                //Integrated Security = SSPI;
                //Initial Catalog = Master;            try
                {
                    fileConnection = new FileStream("..\\..\\sp_attach_db.ini", FileMode.Open);
                }
                catch (FileNotFoundException notfile)
                {
                    MessageBox.Show(notfile.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                StreamReader sr = new StreamReader(fileConnection);
                strsp_attach_db = sr.ReadToEnd();
                if (strsp_attach_db == null)
                {
                    fileConnection.Close();
                    sr.Close();
                    return;
                }
                else
                {
                    fileConnection.Close();
                    sr.Close();
                }            SqlConnection sp = new SqlConnection(@strsp_attach_db);
                string strdbname = @"exec sp_attach_db @dbname = 'BookManager',";
                string strfilename1 = @"'..\..\BookManager_Data.MDF',";
                string strfilename2 = @"'..\..\BookManager_Log.LDF'";
                string ok = strdbname + strfilename1 + strfilename2;
                SqlCommand sqlspcom = new SqlCommand(ok, sp);
                sp.Open();
                sqlspcom.ExecuteNonQuery();
                sp.Close();