I started to learn C # by myself. I learned how to connect to and query databases yesterday and
Code Put it here for fear of forgetting it ~
Components used:
System. Data. sqlclient. sqlconnection
System. Data. sqlclient. sqldataadapter
System. Data. sqlclient. sqlcommand
System. Data. Dataset
Note:
Sqlconnection
Sqlcommand execution Query
Sqldataadapter uses sqlcommand to obtain the result. The result is stored in dataset.
Configuration code: (automatically generated by the system or manually written)
...
This. sqlconnection1.connectionstring = ""; // write the connection string
...
This. sqldataadapter1.selectcommand = This. sqlselectcommand1; // specify the Association
...
This. sqlselectcommand1.commandtext = "select [user], password from m_system"; // query statement
...
The configuration part is better for the system to generate by itself (at least for beginners like me, I am dizzy)
Execute some code:
Try // catch exceptions
{
Sqlconnection1.open (); // you must first connect
DS = new dataset (); // instantiate a dataset
Sqldataadapter1.fill (DS, "m_system"); // query
Textbox1.text = Ds. Tables ["m_system"]. Rows [0] [0]. tostring (); // obtain the result
Textbox2.text = Ds. Tables ["m_system"]. Rows [0] [1]. tostring ();
}
Catch (exception exp)
{
MessageBox. Show (this, exp. tostring ());
}
The table name must be specified in the preceding tables. The rows two-dimensional array specifies the column and column coordinates. I only query one row and two columns.
It looks simple to execute a small amount of code.