Configuration files for database connections in C #

Source: Internet
Author: User
Tags connectionstrings

In c#2010, how do you save and access the connection string for the database?

To add the App. Config file under WinForm, add the Web. config file under ASP.

1. After opening the configuration file, add the relevant code as follows:

<?xml version="1.0" encoding="utf-8"?><configuration> <connectionstrings > <add name="myconn" connectionstring="Data source=.;i Nitial Catalog=northwind; Persist Security info=true; User Id=sa; password="/> </connectionStrings></configuration>     

2. Add a using System.Configuration, and right-click on the item "Add Reference"->. NET component "Using Configuration"

If you do not add references to the component, subsequent code compilation is not possible.

3. The following is the code to read the data

 Privatevoid Button1_Click (Objectsender, EventArgs e) {String connstr = configurationmanager.connectionstrings["myconn"]. ConnectionString; using (SqlConnection conn = new SqlConnection (connstr)) {SqlCommand comm = new SqlCommand ("Selec T FirstName from Employees", conn); Conn. Open (); SqlDataReader SDR = Comm. ExecuteReader (); while (SDR. Read ()) {listBox1.Items.Add (sdr[0]. ToString ()); } } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.