C# 用配置文件连接数据库(Winform和Webform)

引用自:https://blog.csdn.net/sinat_35187039/article/details/82630836

Winform中用配置文件连接数据库

数据库连接类YSqlHelper代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WindowsFormsApp1
{
    public class YSqlHelper
    {

        //配置文件的引用对象ConfigurationManager
        //ConnectionSQLString:配置文件中数据库连接字符串的标签名
        private static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionSQLString"].ConnectionString;

        //查询数据库得到结果放入Datatable并返回
        public static DataTable ExecuteNonQuery(String cmdText,CommandType ct)
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                    {
                        cmd.CommandType = ct;
                        using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            dt.Load(sdr);
                        }
                    }
                }
                catch(Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    System.Diagnostics.Debug.WriteLine(dt.Rows.Count);
                }
            }
                return dt;
        }
    }
}

 

项目配置文件app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <connectionStrings>
    <add name="ConnectionSQLString" connectionString="Data Source=192.168.50.40;Initial Catalog=Training;Persist Security Info=True;User ID=sa;Password=Sitri.123"/>
  </connectionStrings>
</configuration>

在解决方案中选择“引用”,右键选择“添加引用”。 

这里写图片描述
 
搜索system.configuration并勾选添加到引用。 
 这里写图片描述
添加后引用中出现system.configuration,在YSqlHelper类代码头部添加 
using System.Configuration后ConfigurationManager方有效可用。 
 这里写图片描述
测试数据库连接成功,获得dt

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataTable dt = getTable();
        }
        private DataTable getTable()
        {
            string  sql  = "select DISTINCT  DepartmentsID as Dept_id,DepartmentsName as Dept_name,CourseID as Course_id,CourseName as Course_name,CoursePath as Course_path from Course, Department where Course.DepartmentID = Department.DepartmentsID order by DepartmentsID asc, CourseID asc; ";
            DataTable dt = YSqlHelper.ExecuteNonQuery(sql, CommandType.Text);
            return dt;
        }
    } 
}

Webform用配置文件连接数据库

数据库连接帮助类YSqlHelper代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WebForm_2._0
{
    public class YSqlHelper
    {
        private static string connectionString = ConfigurationManager.AppSettings["sqlStr"];
        /// <param name="cmdText">查询SQL语句或存储过程ì</param>
        /// <param name="ct">命令类型</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ExecuteQuery(string cmdText, CommandType ct)
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                System.Diagnostics.Debug.Write(conn);
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                    {
                        cmd.CommandType = ct;
                        using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            System.Diagnostics.Debug.Write(sdr);
                            dt.Load(sdr);
                        }
                    }
                }
                catch(Exception e)
                {
                    System.Diagnostics.Debug.Write(e.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    System.Diagnostics.Debug.Write(dt);
                    System.Diagnostics.Debug.Write(dt.Rows.Count);
                }
            }
            return dt;
        }
    }
}

web配置文件web.config

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

<configuration>
  <appSettings>
    <add key="sqlStr" value="Data Source=192.168.50.40;Initial Catalog=Training;Persist Security Info=True;User ID=sa;Password=Sitri.123"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1"/>
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>

</configution>

测试数据库连接成功,获得dt查询结果:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebForm_2._0
{
    public partial class treeview02 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = getTable();
        }
        private DataTable getTable()
        {
            string sqlStr = "select DISTINCT  DepartmentsID as Dept_id,DepartmentsName as Dept_name,CourseID as Course_id,CourseName as Course_name,CoursePath as Course_path from Course, Department where Course.DepartmentID = Department.DepartmentsID order by DepartmentsID asc, CourseID asc; ";
            DataTable dt = YSqlHelper.ExecuteQuery(sqlStr, CommandType.Text);
            return dt;
        }
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 读取保存App.config配置文件的完整源码参考(转) http://smartsoft.5d6d.com/thread-6550-1-1.html C# 读取保存App.config配置文件的完整源码参考 最近出差在北京做一个小项目,项目里需要读取配置文件的小功能,觉得挺有参考意义的就把代码发上来给大家参考一下。我们选择了直接用微软的读取配置文件的方法。 这个是程序的运行设计效果,就是把这些参数可以进行灵活设置,灵活保存设置状态。 程序编译后自动会产生相应的配置文件,是跟项目的名称一样的配置文件。 读取配置文件及保存配置的具体代码参考如下,希望能给你节省一些时间,直接复制粘贴这个代码就可以用了: //------------------------------------------------------------ // All Rights Reserved , Copyright (C) 2010 , CDPF , Ltd. //------------------------------------------------------------ using System; using System.Configuration; using System.Windows.Forms; using Utilities; namespace DirectSeeding { /// /// FrmConfig /// 读取配置文件 /// /// 修改纪录 /// /// 2011.01.14 版本: 1.0 JiRiGaLa 完善程序的注释等、从新整理代码。 /// /// 版本:1.0 /// /// /// JiRiGaLa /// 2011.01.14 /// /// public partial class FrmConfig : Form { public FrmConfig() { InitializeComponent(); } /// /// 读取配置文件 /// private void GetConfig() { this.txtWriteFileName.Text = ConfigurationManager.AppSettings["WriteFileName"]; this.txtWritePath.Text = ConfigurationManager.AppSettings["WritePath"].Replace("|", Environment.NewLine); this.txtPostMessageURL.Text = ConfigurationManager.AppSettings["PostMessageURL"]; this.txtLeasedLineURL.Text = ConfigurationManager.AppSettings["LeasedLineURL"]; } private void FrmDirectSeeding_Load(object sender, EventArgs e) { this.GetConfig(); } /// /// 保存配置文件 /// private void SaveConfig() { // 写入参数设置 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); configuration.AppSettings.Settings["WriteFileName"].Value = this.txtWriteFileName.Text; configuration.AppSettings.Settings["Wri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值