• 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());
                    }
                }
            }
    复制代码
  • 相关阅读:
    ConcurrentSkipListMap 源码分析
    ConcurrentHashMap 源码分析
    CopyOnWriteArrayList 源码分析
    AtomicBoolean 源码分析
    commons-lang3-3.4.jar
    Effective Java
    FindBugs Bug Descriptions
    EasyMock
    Apache Maven 入门
    Eclipse
  • 原文地址:https://www.cnblogs.com/milantgh/p/3809305.html
Copyright © 2020-2023  润新知