I didn't know how to connect the database when I used to write the data center charging system. This time I had the opportunity to take a good look at this part of the content ···
The relationship between the use of sqlconnection, sqlcommand, and sqldatareader is not very clear. The following describes how to use sqlconnection, sqlcommand, and sqldatareader in combination:
First:
Sqlconnection con = new sqlconnection ();
Con. connectionstring = "Server =.; database = northwind; uid = sa; Pwd =;"; // remove the last semicolon in double quotation marks
Con. open ();
Sqlcommand cmd = con. createcommand ();
Cmd. commandtext = "select * from MERs ";
Sqldatareader SDR = cmd. executereader ();
This. gridview1.datasource = SDR;
This. gridview1.databind ();
SDR. Close ();
Con. Close ();
Second:
Sqlconnection con = new sqlconnection ();
Con. connectionstring = "Server =.; database = northwind; uid = sa; Pwd =;"; // remove the last semicolon in double quotation marks
Con. open ();
Sqlcommand cmd = new sqlcommand ("select * from MERs ");
Cmd. Connection = con;
Sqldatareader SDR = cmd. executereader ();
This. gridview1.datasource = SDR;
This. gridview1.databind ();
SDR. Close ();
Con. Close ();
Third:
This method is most often used, and the connection object is the public object of the entire program. Therefore, I usually encapsulate the database connection in a class so that it can be called anywhere in the program at any time.
Sqlconnection con = new sqlconnection ("Server =.; database = northwind; uid = sa; Pwd =;"); // remove the last semicolon in double quotation marks
Con. open ();
Sqlcommand cmd = new sqlcommand ("select * from MERs", con );
Sqldatareader SDR = cmd. executereader ();
This. gridview1.datasource = SDR;
This. gridview1.databind ();
SDR. Close ();
Con. Close ();
Fourth:
Sqlconnection con = new sqlconnection ();
Con. connectionstring = "Server =.; database = northwind; uid = sa; Pwd =;"; // remove the last semicolon in double quotation marks
Con. open ();
Sqlcommand cmd = new sqlcommand ();
Cmd. Connection = con;
Cmd. commandtext = "select * from MERs ";
Cmd. commandtype = commandtype. text;
// This statement is redundant because it is text by default.
Sqldatareader SDR = cmd. executereader ();
This. gridview1.datasource = SDR;
This. gridview1.databind ();
SDR. Close ();
Con. Close ();
Although these four methods are similar, it is helpful for beginners to understand the relationship between the three and to master this method.