C# 数据库连接测试以及备份

现在我们要做一个如图5.1的数据库连接配置,从界面上看有三个功能需要实现:从配置文件中读取数据库连接的相关属性、备份数据库、测试连接。现在我们就一个一个开始讲解。                                      图5.11.从配置文件中读取数据库连接的相关属性1)  配置文件中的数据库连接:                                             2)  创建一个类,数据库连接类。       ///     /// 数据库连接配置实体    ///     public class CLDBSet    {        ///         /// 数据库连接地址        ///         public string DBAddress        {            get;            set;        }         ///         /// 数据库名        ///         public string DBName        {            get;            set;        }         ///         /// 用户名        ///         public string UserName        {            get;            set;        }         ///         /// 口令        ///         public string PassWord        {            get;            set;        }        ///         /// 是否加密        ///         public bool IsEncrypt        {            get;            set;        }     }3)  从配置文件中获取相应的数据库连接字符串:public class PubConstant{Private static string configFileName=” System.config”; //System.config配置文件名       ///         /// 得到app.config里配置项的数据库连接字符串。        ///      /// 返回CLDBSet 对象       public static CLDBSet GetConnectionString()        {          CLDBSet dbset = new CLDBSet();        //获得配置文件中是否使用加密文件的值          String conSTringEncrypt=System.Configuration.ConfigurationManager. AppSettings["ConStringEncrypt"];         if (ConStringEncrypt.ToLower() == "true")            {                dbset.IsEncrypt = true;            }            else            {                dbset.IsEncrypt = false;           }//获得配置文件中的数据库地址dbset.DBAddress = System.Configuration.ConfigurationManager.AppSettings["DBAddress"];//获得配置文件中的数据库名dbset.DBName = System.Configuration.ConfigurationManager.AppSettings["DBName"]; //获得配置文件中的密码dbset.PassWord = System.Configuration.ConfigurationManager.AppSettings["PassWord"];  //获得配置文件中的口令(密码)dbset.UserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];return dbset;}}4)  在UI界面中显示出当前配置文件中连接的数据库        ///         /// 当窗体加载时就显示        ///        ///    ///         private void FSJKPZ_Load(object sender, EventArgs e)        {          PubConstant  pubConstant=New  PubConstant ();           Var dbSet= pubConstant. GetConnectionString();//数据库连接地址            txtAddress.Text = dbSet.DBAddress;           //用户名            txtUserName.Text = dbSet.UserName;           //口令(密码)            txtPassWord.Text = dbSet.PassWord;            //数据库名            txtSJK.Text = dbSet.DBName;  } 从配置文件中获取当前数据库连接已经算是完成了。2.测试连接测试连接数据库这一块  可以根据输入的服务器地址、用户名、密码、数据库名进行测试连接。1)  先创建一个DBTester类,DBTester类主要写数据库测试连接的方法  public class DBTester{   ///         /// 测试界面输入的数据库连接        ///         /// 数据库连接信息        ///         public object[] TextDBUI(CLDBSet dbSet)        {            bool state = false;            string msg = string.Empty;            object[] o = new object[] { };             SqlConnection con = new SqlConnection(string.Format("database={0};user={1};pwd={2};server={3};Connect Timeout=5", dbSet.DBName, dbSet.UserName, dbSet.PassWord, dbSet.DBAddress));            try            {                con.Open();                if (con.State == System.Data.ConnectionState.Open)                {                    state = true;                }            }            catch (SqlException se)            {                o = new object[] { se.Message, se.Source, se.ErrorCode };                state = false;            }            finally            {                con.Close();            }             if (state)            {                return null;            }            else            {                return o;            }        }} 2)注册点击测试连接按钮事件  ///         /// 注册点击测试连接按钮事件        ///         ///     /// Public void btnTest_Click(object sender, EventArgs e)        {            if (txtAddress.Text.Trim().Equals(""))            {                this.ShowMessageBox(eDialogType.Forbidden, "请输入服务器地址!");                txtAddress.Focus();//为控件设置输入焦点                return;            }            if (txtSJK.Text.Trim().Equals(""))            {                this.ShowMessageBox(eDialogType.Forbidden, "请输入数据库名!");                txtSJK.Focus();//为控件设置输入焦点                return;            }            if (txtUserName.Text.Trim().Equals(""))            {                this.ShowMessageBox(eDialogType.Forbidden, "请输入用户名!");                txtUserName.Focus();//为控件设置输入焦点                return;            }             CLDBSet dbSet = new CLDBSet();            dbSet.DBAddress = txtAddress.Text.Trim();            dbSet.DBName = txtSJK.Text.Trim();            dbSet.UserName = txtUserName.Text.Trim();            dbSet.PassWord = txtPassWord.Text.Trim();             DBTester tester = new DBTester();             object[] result = tester.TextDBUI(dbSet);             if (result == null)            {                this.ShowMessageBox(eDialogType.Success, null, "数据库连接测试成功!");            }            else            {                string s = string.Empty;                s = @"数据库连接测试失败!rn请检查配置的正确性以及网络的正常!" + s;                this.ShowMessageBox(eDialogType.Exception, null, s);            }        } 3.备份数据库1) 写一个方法备份数据库的方法       ///         /// 数据库备份        ///         /// 数据库名称        /// 备份文件路径+名称        ///         public bool BackupDatabase(string dbName, string bakPath)        {            try            {                string bakSql = string.Format(@"use masterbackup database {0} to disk='{1}'", dbName, bakPath);             SqlHelper.ExecuteNonQuery(bakSql, null);            // 注:SqlHelper是一个数据库的帮助类            }            catch            {                return false;            }            return true;        }1)  注册备份数据库按钮点击事件  private void btnBackup_Click(object sender, EventArgs e)        {        //获得配置文件中的数据库连接          PubConstant pubConstant=New PubConstant();          Var dbset=  pubConstant. GetConnectionString(); //从配置文件中获得的数据库连接   string dbName = dbSet.DBName; //获得数据库名string bakPath = "";       SaveFileDialog saveFileDialog1 = new SaveFileDialog();       saveFileDialog1.Filter = "BAK文件|*.bak";//类型是备份文件      saveFileDialog1.FileName = dbName+DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak"; //备份后的文件名 数据库名+当前时间if (saveFileDialog1.ShowDialog() == DialogResult.OK)            {                 bakPath = saveFileDialog1.FileName;                 if (BackupDatabase(dbName, bakPath))                {                    this.ShowMessageBox(eDialogType.Success, "数据库备份成功!");                }                else                {                    this.ShowMessageBox(eDialogType.Exception, "数据库备份失败!");                }            }        }  }    

相关内容推荐