First, the tools used
Visual Studio 2017 and SQL Server Management Studio 2012
Second, the connection
Open SQL Server Management Studio 2012, click New Query, create the database from the code as follows:
1Create DATABASE Data1--Create a database2Go--go represents the following statement, which is based on the previous statement execution.3Use Data1--Determining Operational Database Objects4 Go5CREATE TABLE Users--Add a table to the database6 (7CodeintIdentity1,1) primary key,--define a self-growing column and set the primary key8Username varchar ( -) notNULL,--Accountcolumn, not empty9Password varchar ( -) notNULL--password column, not emptyTen ) OneInsert into users values ('CFF',111) --add data to the users table in the database - Select* fromUsers--Querying Data theDelete fromUsers
Open Visual Studio 2017 and create a new form program with the following form interface:
Click Tools on the Visual Studio 2017 menu bar to connect to the database. :
Click Test Connection succeeded as shown:
Next, connect the database with code as follows:
private void Button_queding_click (object sender, EventArgs e) {string zhanghao= Textbox_zhanghao. Text, Mima= Textbox_mima. Text; Create an object for the database connection class SqlConnection con = new SqlConnection (@ "Data source=cff-pc;initial catalog=data1;integrated secur Ity=true "); Turn the connection on con. Open (); The function that executes the Con object returns an object of type SqlCommand SqlCommand cmd = con. CreateCommand (); The input data is stitched into an SQL statement and handed to the Cmd object cmd. CommandText = "SELECT * from Users where username= '" + Zhanghao + "' and password= '" + Mima + "'"; Executing the statement with the CMD function, returning the SqlDataReader object DR,DR is the returned result set (that is, the table data queried in the database) SqlDataReader dr = cmd. ExecuteReader (); With Dr's read function, each time it is executed, it returns a collection of the next row of data Dr, before executing the Read function, the DR is not a set if (Dr. Read ()) {//dr[] can be filled with a column name or index, showing the obtained data MessageBox.Show (Dr[1]. ToString ()); }//Close the connection after use to avoid affecting other programs accessing con. Close (); }
The results of the implementation are as follows:
C # form programs linked to SQL Sever database