Use C # to implement the user name login---Connect to the database, query and determine if there is a user name
First, the link class
1. Add DbConnection Class
2 Construction
public class DBConnection { private static string _connectionstring = null; public static SqlConnection Connection { get { //reads the link string from the configuration file _connectionstring = configurationmanager.connectionstrings["MyDB"]. ConnectionString; Building a Connection object using a link string SqlConnection conn = new SqlConnection (_connectionstring); Return conn;}} }
(You can also define a string variable in get{} to receive the configuration)
public class DBConnection {public static SqlConnection Connection { get } //Read link string from configuration file string _connectionstring = configurationmanager.connectionstrings["MyDB"]. ConnectionString; Building a Connection object using a link string SqlConnection conn = new SqlConnection (_connectionstring); Return conn;}} }
Second, add the configuration file
1. Reference right-click to add System.Configuration reference
2. Add New Item--Application configuration file
3.app.config
<connectionStrings> <add name= "mydb" connectionstring= "server=.; Database=mydb;uid=sa;pwd=123 "/> </connectionStrings>
Note: The name name in the configuration file is the same as the field in Connectionstring["" in the DbConnection class
Third, open the close database
The 1.Main function calls the Connection property inside the DbConnection class
Class program { static void Main (string[] args) { SqlConnection conn = dbconnection.connection; Console.WriteLine (Conn. State); Conn. Open (); Console.WriteLine (Conn. State); Conn. Close (); Console.WriteLine (Conn. State); } }
Execution results
C # Connection database--commonly used at present