C#中的数据库配置和连接

1.  向项目添加 app.config 文件:
右击项目名称,选择 添加 添加新建项 ,在出现的 添加新项 对话框中,选择 添加应用程序配置文件 ;如果项目以前没有配置文件,则默认的文件名称为 “app.config” ,单击 确定 。出现在解决方案资源管理器中的 app.config 文件为:
<? xml version ="1.0" encoding ="utf-8" ?>

< configuration >

    

</ configuration >
2.  connectionStrings 配置节:
请注意:如果您的 SQL 版本为 2005 Express 版,则默认安装时 SQL 服务器实例名为 localhost\SQLExpress ,须更改以下实例中 “Data Source=****;” 一句为 “Data Source=localhost\SQLExpress;” ,在等于号的两边不要加上空格。
如本例中:
< connectionStrings >

         < clear />

         < add name ="ProConnectionString" connectionString ="Data Source=172.18.139.215;Initial Catalog=NEWDB;User ID=dba;Password=dba" />

     </ connectionStrings >

3. appSettings 配置节:
appSettings 配置节为整个程序的配置,如果是对当前用户的配置,请使用 userSettings 配置节,其格式与以下配置书写要求一样。
< appSettings >

         < add key ="isFirstRunSystem" value ="true" />

     </ appSettings >

 
C# 中的数据库配置
App.config 文件:
 
<? xml version ="1.0" encoding ="utf-8" ?>

< configuration >

    

     < appSettings >

         < add key ="isFirstRunSystem" value ="true" />

     </ appSettings >

</ configuration >

4. 读取和更新配置节
FrmDBConfig.cs

/*----------------------------------------------------------------

        // Copyright (C) Project

        // 文件名:

        // 文件功能描述:进行数据库配置和连接

        //

        //    

        // 创建标识:

        //

        // 修改标识:

        // 修改描述:

----------------------------------------------------------------*/

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.ProviderBase;

using System.Data.SqlClient;

namespace Kitchen.UI

{

         public partial class FrmDBConfig : Form

        {

                 public FrmDBConfig()

                {

                        InitializeComponent();

                        BindDataServer();

                }

                 public FrmDBConfig(FrmWelcome fw)

                {

                        InitializeComponent();

                        BindDataServer();

                        fw.Close();

                }

                 /// <summary>

                 /// 测试数据库连接

                 /// </summary>

                 /// <param name="sender"></param>

                 /// <param name="e"></param>

                 private void button1_Click( object sender, EventArgs e)

                {

                         if (txtPassWord.Text.Trim() == "" || cbServerName.Text.Trim() == "" || txtUsername.Text.Trim() == "")

                        {

                                MessageBox.Show( "输入服务器名(或者IP)、用户名和密码");

                                 return;

                        }

                         string connStr = string.Format( "Data Source={0};User ID={1};Password={2}", cbServerName.Text.Trim(), txtUsername.Text.Trim(), txtPassWord.Text.Trim());

                        SqlConnection conn = new SqlConnection(connStr); // sqlcp = new SqlClientPermission()

//建立连接

                         try

                        {

                                 //myConn = new SqlConnection(connStr);

                                conn.Open();

                        }

                         catch (Exception ee)

                        {

                                MessageBox.Show( "连接失败");

                                 return;

                        }

                        MessageBox.Show( "连接成功");

                        

                }

    

                 private void button4_Click( object sender, EventArgs e)

                {

                         this.Close();

                }

    

                 private void button2_Click( object sender, EventArgs e)

                {

                         if (txtPassWord.Text.Trim() == "" || cbServerName.Text.Trim() == "" || txtUsername.Text.Trim() == "")

                        {

                                MessageBox.Show( "输入服务器名(或者IP)、用户名和密码");

                                 return;

                        }

                         if ((System.Configuration.ConfigurationSettings.AppSettings.GetValues( "isFirstRunSystem"))[0] == "true")

                        {

                                 try

                                {

                                         string str = string.Format( "data source ={0};initial catalog={1};user id={2};password={3};",

                                                cbServerName.Text.Trim(), txtDBName.Text.Trim(), txtUsername.Text.Trim(), txtPassWord.Text);

                                        Kitchen.Util.Config cc = new Kitchen.Util.Config();

                                        cc.UpdateDBConfig( "ProConnectionString ", str, "System.Data.SqlClient");

                                        MessageBox.Show( "配置成功,软件将自动重启动。"); //更新配置节

                                        cc.UpdateConfig( "isFirstRunSystem", "false"); //更新配置节

                                         this.Close();

                                        Application.Restart();

                                }

                                 catch (Exception ee)

                                {

                                        MessageBox.Show( "配置失败\n" + ee.Message, "错误");

                                }

                        }

                         else

                        {

                                 try

                                {

                                         string str = string.Format( "data source ={0};initial catalog={1};user id={2};password={3};",

                                                cbServerName.Text.Trim(), txtDBName.Text.Trim(), txtUsername.Text.Trim(), txtPassWord.Text);

                                        Kitchen.Util.Config cc = new Kitchen.Util.Config();

                                        cc.UpdateDBConfig( "ProConnectionString ", str, "System.Data.SqlClient");

                                         if (MessageBox.Show( "更新成功,是否重新启动软件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)

                                        {

                                                 this.Close();

                                                Application.Restart();

                                        }

                                         else

                                        {

                                                 this.Close();

                                        }

                                }

                                 catch (Exception ee)

                                {

                                        MessageBox.Show( "配置失败\n" + ee.Message, "错误");

                                }

                        }

                }

    

                 private void BindDataServer()

                {

                        System.Data.Sql.SqlDataSourceEnumerator sdse = System.Data.Sql.SqlDataSourceEnumerator.Instance;

                        DataTable dt = sdse.GetDataSources();

                        cbServerName.DataSource = dt;

                        cbServerName.DisplayMember = "ServerName";

                }

        }

}

Config.cs 文件:
/*----------------------------------------------------------------/

Copyright (C)版权所有。

    

文件名:

文件功能描述:更新connectionStrings配置节

    

修改标识:

修改描述:

    

/----------------------------------------------------------------*/

    

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.Windows.Forms;

namespace Kitchen.Util

{

         public class Config

        {

                 //更新app.config的函数

                 //配置文件的源文件

    

                 //<?xml     version="1.0"     encoding="utf-8"     ?>        

                 //<configuration>        

                 //<appSettings>        

                 //<add     key="ServerName"     value=""/>        

                 //</appSettings>        

                 //</configuration>    

                 /// <summary>

                 /// 更新app.config的数据库连接字符串函数

                 /// </summary>

                 /// <param name="connstrname">连接字符串名称</param>

                 /// <param name="connstr">连接字符串</param>

                 public     void     UpdateDBConfig( string     connstrname, string connstr, string providername)

                {        

                        XmlDocument     doc     =     new     XmlDocument();        

                        doc.Load(Application.ExecutablePath+ ".config");

                        XmlNode node = doc.SelectSingleNode( @"//add[@name='" + connstrname + "']");        

                        XmlElement     ele     =     (XmlElement)node;

                        ele.SetAttribute("connectionString", connstr);

                        ele.SetAttribute("providerName", providername);

                        doc.Save(Application.ExecutablePath+".config");            

                }

    

                /// <summary>

                /// 修改config中<add key ='keyname' value='keyvalue' />

                /// </summary>

                /// <param name="keyname">键名称</param>

                /// <param name="keyvalue">键值</param>

                public void UpdateConfig(string keyname,string keyvalue)                {

                        XmlDocument doc = new XmlDocument();

                        doc.Load(Application.ExecutablePath + ".config");

                        XmlNode node = doc.SelectSingleNode(@"//add[@key='" + keyname + "']");

                        XmlElement ele = (XmlElement)node;

                        ele.SetAttribute("value", keyvalue);

                        doc.Save(Application.ExecutablePath + ".config");

                }        

    

    

        }

}

    
 

你可能感兴趣的:(数据库,C#,配置,连接,休闲)