C#批量附加指定目录下的所有数据库文件到数据库(2)

if (n == -1)
                    {
                        strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + "_log.ldf";
                        strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + ".ldf";
                    }
                    else
                    {
                        strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("_"));
                        strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + "_log.ldf";
                        strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + ".ldf";
                    }

StringBuilder sb = new StringBuilder();
                    sb.Append("sp_attach_db @dbname='" + strDataFileName + "',@filename1='" + strMdfFilePath + "'");
                    if (System.IO.File.Exists(strLogFilePath))
                    {
                        sb.Append(",@filename2='" + strLogFilePath + "'");
                        AttachDataBase(sb.ToString());
                    }
                    else if (System.IO.File.Exists(strLdfFilePath))
                    {
                        sb.Append(",@filename2='" + strLdfFilePath + "'");
                        AttachDataBase(sb.ToString());
                    }
                    else
                    {
                        Console.WriteLine("数据库文件" + strMdfFilePath + "缺少必备的日志文件!");
                    }
                }
            }
        }
        /// <summary>
        /// 连接数据库并执行附加对应的数据库文件命令
        /// </summary>
        /// <param>附加数据库命令字符串</param>
        /// <returns></returns>
        private bool AttachDataBase(string strSql)
        {
            SqlConnection con = new SqlConnection(@"Data Source=(local);Initial Catalog=master;Integrated Security=True");
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = strSql;
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                //如果数据库中存在名为要添加的数据库时则抛出异常
                Console.WriteLine("附加数据库时异常:" + ex.Message);
                return false;
            }
            finally
            {
                con.Close();
            }
        }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/wyyydw.html