zoukankan      html  css  js  c++  java
  • C#中数据库连接的配置文件

    在C#2010中,如何保存和访问数据库的连接字符串呢?

    在Winform下要新增App.config文件,在Asp.net下要新增web.config文件。

    1.打开配置文件添加相关代码后如下即可:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="myconn" connectionString="Data Source=.;Initial Catalog=Northwind;
             Persist Security Info=True;User ID=sa;Password=110"/>
      </connectionStrings>
    </configuration>

    2.添加using System.Configuration;并在项目上右键“添加引用”->.Net组件中"Using Configuration"

    如果不在组件中添加引用的话,后续的代码编译不过。

    3.如下为读取数据的相关代码

     private void button1_Click(object sender, EventArgs e)
            {
                string connstr = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connstr))
                {
                    SqlCommand comm = new SqlCommand("select FirstName from Employees", conn);
                    conn.Open();
                    SqlDataReader sdr = comm.ExecuteReader();
                    
                    while (sdr.Read())
                    {
                        listBox1.Items.Add(sdr[0].ToString());
                    }
                }
            }
  • 相关阅读:
    docker常用命令
    docker安装注意事项
    DataGridView中实现自动编号
    Flask设置配置文件
    python路径找类并获取静态字段
    JavaScript数据类型
    php学习笔记6
    php学习笔记5
    php学习笔记4
    php学习笔记3
  • 原文地址:https://www.cnblogs.com/yagzh2000/p/2957266.html
Copyright © 2011-2022 走看看