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

摘要:
=“”){strFileFolder=myFolderBrowserDialog.SelectedPath;}//查找所有MDF文件的列表string[]arrAttachFilePath=null;如果(strFileFolder!=“”){DirectoryInfodir=newDirectoryInfo;//判断主数据库文件FileInfo[]finfo=dir.GetFiles;如果{arrAttachFilePath=newstring[finfo.Length};如果{int i=0;foreach{arr AttachFilePath[i]=f.FullName;i=i+1;If=j}如果(arrAttachFilePath!

应用场合:因为经常更换操作系统,所以D盘存放数据库文件目录的数据库每次都要一个一个的附加到MSSQL中,因此设计程序批量附加省时间也方便自己和大家。

程序不足:没有去研究跟实现NDF日志文件附加和多个日志文件的数据库附加。

程序源码:


        /// <summary>
        /// 循环查找指定目录下要附加的数据库文件和对应的日志文件,连接本地数据库并执行数据库附加命令
        /// </summary>
        private void AttachFolderDB()
        {
            string strFileFolder = "";
            FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
            myFolderBrowserDialog.ShowDialog();
            if (myFolderBrowserDialog.SelectedPath != "")
            {
                strFileFolder = myFolderBrowserDialog.SelectedPath;
            }
            //查找所有的MDF文件列表
            string[] arrAttachFilePath = null;
            if (strFileFolder != "")
            {
                DirectoryInfo dir = new DirectoryInfo(strFileFolder);
                //判断目录下是否存在主数据库文件
                FileInfo[] finfo = dir.GetFiles("*.mdf");
                if (finfo.Length > 0)
                {
                    arrAttachFilePath = new string[finfo.Length];
                    if (finfo.Length > 0)
                    {
                        int i = 0;
                        foreach (FileInfo f in finfo)
                        {
                            arrAttachFilePath[i] = f.FullName;
                            i = i + 1;
                        }
                    }
                }

            }
            //循环附加数据库
            if (arrAttachFilePath != null)
            {
                for (int i = 0; i < arrAttachFilePath.Length; i++)
                {
                    string strFile = arrAttachFilePath[i].ToString();
                    string strMdfFilePath = arrAttachFilePath[i].ToString();//mdf路径
                    string strLogFilePath = "";//日志文件路径
                    string strLdfFilePath = "";//日志文件路径
                    string strDataFileName = strMdfFilePath.Substring(strMdfFilePath.LastIndexOf("\\") + 1, strMdfFilePath.Length - strMdfFilePath.LastIndexOf("\\") - 1);
                    strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("."));

                    string logIndex = "_Data";
                    int n = strDataFileName.IndexOf(logIndex);

                    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 name="strSql">附加数据库命令字符串</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();
            }
        }

免责声明:文章转载自《C#批量附加指定目录下的所有数据库文件到数据库中》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇中国大学mooc机器学习第一天-学期导学3.1 队列-顺序存储下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Lua字符串及模式匹配

字符类基础函数举例介绍: string.len( ‘string’ ) string.lower( ‘string’ ) string.upper( ‘string’ ) string.rep( ‘a’ , 5 ) ==> aaaaa string.sub( ‘string’ , I , j ) string.sub(...

Redis集群下过期key监听

1. 前言 在使用redis集群时,发现过期key始终监听不到。网上也没有现成的解决方案。于是想,既然不能监听集群,那我可以建立多个redis连接,分别对每个redis的key过期进行监听。以上做法可能不尽人意,目前也没找到好的解决方案,如果有好的想法,请留言告知哦!不多说,直接贴我自己的代码! 2. 代码实现 关于Redis集群配置代码此处不贴,直接贴配...

STM32自己的封装库

以前一直使用STM32的标准库,需要一步步地将代码加进去,将编译选项设置好,然后再编译整个工程。 这个编译过程是一个相当慢的过程!完全编译大约需要一支烟的时间。每次建立工程都这么编译,是一个相当浪费时间和香烟的过程。 于是,我有了将库编译成lib文件的想法。本博文就是我将STM32F4的标准库编译成lib文件并在工程中使用的过程。 适用对象: 1、熟悉库...

Linux搭建主从数据库服务器(主从复制)

配置主机数据库: 1.克隆linux操作系统             2.修改Linux系统主机IP地址   主机IP:192.168.247.150   从机IP:192.168.247.151        3.通过xshell连接Master 连接主机IP:ssh 192.168.247.150   这里有可能连接失败。   方案一:将虚拟机的网络适...

三、Electron + Webpack + Vue 搭建开发环境及打包安装 ---- 打包electron应用

目录 Webpack + Vue 搭建开发环境及打包安装 ------- 打包渲染进程 Electron + Webpack  搭建开发环境及打包安装 ------- 打包主进程 Electron + Webpack + Vue 搭建开发环境及打包安装 ---- 打包electron应用 三、打包Election App 应用   在之前的节中已经写...

pytest框架+allure2框架的基本使用(2019-09-03更新)

前提准备: pip安装allure-pytest、pytest和allure-python-commons包,安装过程如下图: pip install allure-pytest pip install pytest pip install allure-python-commons 安装成功如下: allure --version 2.12.1 py...