The database plays an important role in software development, and basically all major projects will use the database. Now I mainly briefly introduce SQL Server 2008 C # operation, by learning C # database operation basis, then extrapolate, open thinking, can be a large project database software development.
1. Connection database (Connection object)
// connect database strconn = server=gordon-pc\\ sqlexpress;database=db_ghc;uid=sa;pwd=123456 " // string strconn = @ "Data source=localhost\sqlexpress;initial catalog=db_ghc;integrated Security=true "; SqlConnection connsql = new SqlConnection ( strconn); Connsql.open (); if (connsql.state == ConnectionState.Open) {MessageBox.Show ( " connection successful "
Note that the database operation is completed in a timely manner to close the connection, code as follows:
Connsql.dispose (); // or Connsql.close ();
After you close the connection using the Close method, you can open the connection again by opening it, and you cannot use the Open method to open the connection after you close the connection with the Dispose method, and you must reinitialize the connection again and open it again.
2. Execute SQL Statement (Command object)
stringstrconn ="server=gordon-pc\\sqlexpress;database=db_ghc;uid=sa;pwd=123456"; SqlConnection Connsql=NewSqlConnection (strconn); Connsql.open (); SqlCommand Cmdsql=NewSqlCommand (); Cmdsql.connection=Connsql;cmdsql.commandtext="SELECT * from TB_GHC"; Cmdsql.commandtype=CommandType.Text; SqlDataReader Readersql=Cmdsql.executereader (); while(Readersql.read ()) {LISTVIEW1.ITEMS.ADD (readersql[0]. ToString ());//read data table [0] column}connsql.dispose ();
ExecuteReader method: Executes the SQL statement and generates an instance of the SqlDataReader object that contains the data.
The DataReader object is a data-read object that is useful for reading data quickly without modifying the data.
Connect to the database and execute the SQL statement, or use the following code to do it:
New SqlConnection ("server=gordon-pc\\sqlexpress;database=db_ghc;uid=sa;pwd=123456" New SqlCommand ("select * from TB_GHC", Connsql);
3. Data adapter (DataAdapter) and data set (dataset)
The DataAdapter object is a data adapter object that is a bridge between a dataset and a data source.
A DataSet object is like a small database stored in memory that can contain data tables, columns of data, rows of data, views, constraints, and relationships. Typically, data from a dataset originates from an XML or database. To get data from a database, you use the data adapter DataAdapter to query the specified data from the database, and then populate the dataset with that object's Fill method.
4. Display the data to the user (DataGridView control)
You set the DataSource property of the DataGridView control to the tabular data of the dataset so that it displays the data in the data table.
Database Operations (C #)