Environment: VS2010 + SQL Server 2008
First, according to the object-oriented program design idea, design a database tool class MyTool.cs, which encapsulates the method of database connection and operation, each function module can only call the corresponding function when the database operation is required.
//the namespaces introducedusingSystem.Data.SqlClient;//namespaces for SQL Sever data accessusingSystem.Data;//namespace of the dataset classusingSystem.Windows.Forms;//DataGridView Namespace for control classes//executes the specified SQL command statement (insert,delete,update, etc.) and returns the number of rows affected by the command Public Static intExecuteCommand (stringsqlstr) {SqlConnection SqlConnection1=NewSqlConnection ("server=dell-pc;database=11071312hotelsys;uid=sa;pwd=xiaoyi9421");//Create a database connection (my personal database information is in the string)Sqlconnection1.open ();//Open a database connectionSqlCommand SqlCommand1 =NewSqlCommand (Sqlstr, SqlConnection1);//Execute SQL command intSuccnum =Sqlcommand1.executenonquery (); returnSuccnum;}//query (SELECT) specifies the data record, and populates the data control in the GridView Public Static voidQuerydatatogrid (stringsqlstr, DataGridView dataGridView1) {SqlConnection SqlConnection1=NewSqlConnection ("server=dell-pc;database=11071312hotelsys;uid=sa;pwd=xiaoyi9421");//Create a database connectionSqlDataAdapter sqlDataAdapter1 =NewSqlDataAdapter (Sqlstr, SqlConnection1);//Create a data adapter using the SqlConnection1 you have created SqlDataAdapter1DataSet DataSet1 =NewDataSet ();//To Create a DataSet objectSqlDataAdapter1.Fill (DATASET1);//execute the query, and the results of the query are stored in the data set .Datagridview1.datasource = dataset1.tables[0];//bind data to DataGridView1}
When database operations are required in each function module, just specify the SQL statement to execute, invoke the methods in the Database Tools class, and give some basic SQL operations (single table)
//IncreaseSqlstr ="INSERT into table name (column name 1, column name 2) VALUES (insert value 1, insert value 2)";//executes the specified SQL command statement and returns the number of rows affected by the commandintSuccnum =Mytool.executecommand (SQLSTR);if(Succnum >0) MessageBox.Show ("Entry Success");//DeleteSqlstr ="Delete from table name where delete condition";intSuccnum =Mytool.executecommand (SQLSTR);if(Succnum >0) MessageBox.Show ("Delete succeeded");//ChangeSqlstr ="Update table name set column Name 1 = update value 1, column Name 2 = update Value 2";intSuccnum =Mytool.executecommand (SQLSTR);if(Succnum >0) MessageBox.Show ("Update Successful");//CheckSqlstr ="Select Column Name 1, column name 2 from table name where query expression"; Mytool.querydatatogrid (Sqlstr, dataGridView1);//populating the Data Control DataGridView
C # Connecting a SQL Server database for simple operations