C # SQL Server database operation (reprint) C # SQL Server database operations

This article is reproduced from  https://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html

C # SQL Server database operations

1 Overview

ado.net provides a rich database operations, these operations can be divided into three steps:

  • First, using SqlConnection object database connection;
  • Second, to establish the SqlCommand object, and call stored procedures responsible for the implementation of SQL statements;
  • Third, the SQL or stored procedure returns execution after "result" of operation.

To return to the "Results" operations can be divided into two categories:

  • First, by using the direct line by line SqlDataReader read data set;
  • Second, the United DataSet SqlDataAdapter to operate the database.

Both comparison:

  • SqlDataReader in time with the remote database connected to the server, the remote data forms "flow" of the one-way transmission to the client, it is "read-only". Because it is direct access to the database, it is more efficient, but not convenient to use.
  • DataSet disposable acquired from the data source to the local data, and create a mini-database (comprising tables, rows, columns, the relationship between the rules, tables, etc.) locally, may be disconnected during the connection to the server, using the operation SqlDataAdapter object " local mini-database ", after the one-time update to a remote database server by SqlDataAdapter. This approach uses up more square, it is simple. But a little bit worse performance than the first. (In the general case of both properties is negligible.)

A very well-known ADO.NET architecture diagram:

2, the connection string wording

string connectString = "Data Source=.;Initial Catalog=Student;Integrated Security=True";

3, SqlConnection Object

Namespace: System.Data.SqlClient.SqlConnection;

Returns database connection object, parameter string. Examples of "connection object", and opens the connection

SqlConnection sqlCnt = new SqlConnection(connectString);
sqlCnt.Open();

After completion of use, and needs to close "connection object"

sqlCnt.Close();

4, SqlCommand Object

Namespace: System.Data.SqlClient.SqlCommand;

SqlCommand object for performing database operations, the operation in three ways:

  • SQL语句:command.CommandType = CommandType.Text;
  • Stored procedure: command.CommandType = CommandType.StoredProcedure;
  • Entire table: command.CommandType = CommandType.TableDirect;

Examples of a SqlCommand object

Command new new = the SqlCommand the SqlCommand (); 
command.Connection = sqlCnt; // bind SqlConnection object

Or created directly from SqlConnection

SqlCommand command = sqlCnt.CreateCommand();     

Common methods:

  • command.ExecuteNonQuery (): returns the affected function, such as add, delete, change operation;
  • command.ExecuteScalar (): execute the query and returns the results of the first line of the first column;
  • command.ExecuteReader (): returns a data stream (the SqlDataReader object).

Common Operations

① execute SQL
SqlCommand cmd = conn.CreateCommand (); // create a SqlCommand object 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "from the SELECT * Products's @ID ="; // SQL statement 
cmd.Parameters.Add ( "@ ID" , SqlDbType.Int); 
. cmd.Parameters [ "@ ID"] = the Value. 1; // parameters sql statement to assign
② call a stored procedure
SqlCommand cmd = conn.CreateCommand();                      
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "存储过程名";
③ the entire table
SqlCommand cmd = conn.CreateCommand();    
cmd.CommandType = System.Data.CommandType.TableDirect;
cmd.CommandText = "表名"

5, SqlDataReader Object

Namespace: System.Data.SqlClient.SqlDataReader;

SqlDataReader object provides functions to read only one-way data, unidirectional: only data sequentially read next; read-only: the DataReader data is read-only, can not be modified; data corresponding to DataSet can read and modify any .

It has a very important method is the Read (), the return value is a Boolean value, is to advance to the next data, a section of the return data is executed, when the jump is false boolean value is true. Such as

= New new of the SqlCommand the Command of the SqlCommand (); 
command.Connection = sqlCnt; 
command.CommandType = CommandType.Text; 
command.CommandText = "* from the Select the Users"; 
SqlDataReader = Command.ExecuteReader Reader (); // execute SQL, returns a " stream " 
the while (reader.Read ()) 
{ 
    Console.Write (Reader [" username "]); // print out each user's user name 
}

6, DataSet objects

6.1 SqlDataAdapter;

Namespace: System.Data.SqlClient.SqlDataAdapter;

Is a bridge between SqlCommand SqlDataAdapter and DataSet, SqlDataAdapter object instantiated:

The SqlConnection = new new sqlCnt the SqlConnection (connectString); 
sqlCnt.Open (); 

// creation of the SqlCommand 
of the SqlCommand the MySqlCommand = new new of the SqlCommand (); 
mySqlCommand.CommandType = CommandType.Text; 
mySqlCommand.CommandText = "from the SELECT * Product"; 
mySqlCommand.Connection = sqlCnt; 

// create a SqlDataAdapter 
SqlDataAdapter myDataAdapter = new new SqlDataAdapter (); 
myDataAdapter.SelectCommand = the MySqlCommand; // to be executed for the SqlDataAdapter object bound SqlCommand object

SQL can be simplified as above

The SqlConnection = new new sqlCnt the SqlConnection (connectString); 
sqlCnt.Open (); 
// hide the definition SqlCommand objects while hiding bound SqlCommand object and SqlDataAdapter object 
SqlDataAdapter myDataAdapter = new SqlDataAdapter ( "select * from product", sqlCnt) ;
Properties and Methods
  • myDataAdapter.SelectCommand properties: SqlCommand variable package Select statement;
  • myDataAdapter.InsertCommand properties: SqlCommand variable package Insert statement;
  • myDataAdapter.UpdateCommand properties: SqlCommand variable package Update statement;
  • myDataAdapter.DeleteCommand properties: SqlCommand variable package Delete statements.
  • myDataAdapter.fill (): The execution results are filled in the Dataset, hides open SqlConnection and perform SQL operations.

6.2 SqlCommandBuilder;

Namespace: System.Data.SqlClient.SqlCommandBuilder.

The operation of the DataSet (change, add, delete) only in local modifications, to submit to the "database" is required SqlCommandBuilder object. After the client for editing the data, the overall update data. Specific usage is as follows:

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder (myDataAdapter) ; // function to myDataAdapter given SqlCommandBuilder 
myDataAdapter.Update (myDataSet, "table"); // DataSet submitted after the changes to the database, the second parameter is the name of a stored table in the DataSet, not a real database table names (both the same in most cases).

6.3 DataSet

Namespace: System.Data.DataSet.

Data collection, local micro database can store multiple tables.

The first step is to use DataSet SqlDataAdapter return data sets (Tables) filled Dataset object:

= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); 
the DataSet myDataSet the DataSet new new = (); // Create the DataSet 
myDataAdapter.Fill (myDataSet, "Product"); // returns the data set as a "table" fill the DataSet, database table names may be different from the real table does not affect the subsequent add, delete, change operations and the like
① access data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

DataTable myTable = myDataSet.Tables["product"];
foreach (DataRow myRow in myTable.Rows) {
    foreach (DataColumn myColumn in myTable.Columns) {
        Console.WriteLine(myRow[myColumn]);	//遍历表中的每个单元格
    }
}
② modify data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

// 修改DataSet
DataTable myTable = myDataSet.Tables["product"];
foreach (DataRow myRow in myTable.Rows) {
    myRow["name"] = myRow["name"] + "商品";
}

// 将DataSet的修改提交至“数据库”
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Update(myDataSet, "product");

Note:. "For does not return any key column information SelectCommand, UpdateCommand does not support dynamic SQL generation" must be defined in a primary key modify, and delete tables product, select the field must also contain a primary key, otherwise it will prompt an error

③ add a line
= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); 
the DataSet myDataSet the DataSet new new = (); 
myDataAdapter.Fill (myDataSet, "Product"); 
the DataTable myTable myDataSet.Tables = [ "Product"]; 

// Add line 
the DataRow myRow myTable.NewRow = (); 
myRow [ "name"] = "Giant"; 
myRow [ ". price"] = 13.2; 
// myRow [ "ID"] = 100; if the ID is "Auto growth", this at may not be provided, even if the setting is also invalid 
myTable.Rows.Add (myRow); 

// modified DataSet submitted to "database" 
the SqlCommandBuilder MySqlCommandBuilder the SqlCommandBuilder new new = (myDataAdapter); 
myDataAdapter.Update (myDataSet, "Product");
④ delete a row
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

// 删除第一行
DataTable myTable = myDataSet.Tables["product"];
myTable.Rows[0].Delete();

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Update(myDataSet, "product");
Attributes
  • Tables: obtaining a set of tables contained in the DataSet.
  • Relations: get used to link the table and allows you to browse the collection from the parent table to the child table relationships.
  • HasEroors: Indicates whether the value has been initialized DataSet object.
method
  • Clear Clear all DataSet object data for all tables.
  • Clone DataSet object copied to another structure DataSet object, the copy includes all structures, relationships and constraints, but does not contain any data.
  • Copy The data structures and objects to another DataSet DataSet object. Exactly the same two DataSet objects.
  • CreateDataReader DataTableReader returns with a result set for each DataTable object, the display order of the same order Tables collection of tables.
  • Dispose Releases resources DataSet object occupies.
  • Reset will initialize the DataSet object.

7, free up resources

After use of resources should be released promptly and close the connection, as follows:

myDataSet.Dispose (); // release DataSet object 
myDataAdapter.Dispose (); // release SqlDataAdapter object 
myDataReader.Dispose (); // release the SqlDataReader 
sqlCnt.Close (); // close the connection 
sqlCnt.Dispose (); // release the database connection object

 

Links: Beijing Aerospace Control Technology Co., Ltd. in Switzerland

1 Overview

ado.net provides a rich database operations, these operations can be divided into three steps:

  • First, using SqlConnection object database connection;
  • Second, to establish the SqlCommand object, and call stored procedures responsible for the implementation of SQL statements;
  • Third, the SQL or stored procedure returns execution after "result" of operation.

To return to the "Results" operations can be divided into two categories:

  • First, by using the direct line by line SqlDataReader read data set;
  • Second, the United DataSet SqlDataAdapter to operate the database.

Both comparison:

  • SqlDataReader in time with the remote database connected to the server, the remote data forms "flow" of the one-way transmission to the client, it is "read-only". Because it is direct access to the database, it is more efficient, but not convenient to use.
  • DataSet disposable acquired from the data source to the local data, and create a mini-database (comprising tables, rows, columns, the relationship between the rules, tables, etc.) locally, may be disconnected during the connection to the server, using the operation SqlDataAdapter object " local mini-database ", after the one-time update to a remote database server by SqlDataAdapter. This approach uses up more square, it is simple. But a little bit worse performance than the first. (In the general case of both properties is negligible.)

A very well-known ADO.NET architecture diagram:

2, the connection string wording

string connectString = "Data Source=.;Initial Catalog=Student;Integrated Security=True";

3, SqlConnection Object

Namespace: System.Data.SqlClient.SqlConnection;

Returns database connection object, parameter string. Examples of "connection object", and opens the connection

SqlConnection sqlCnt = new SqlConnection(connectString);
sqlCnt.Open();

After completion of use, and needs to close "connection object"

sqlCnt.Close();

4, SqlCommand Object

Namespace: System.Data.SqlClient.SqlCommand;

SqlCommand object for performing database operations, the operation in three ways:

  • SQL语句:command.CommandType = CommandType.Text;
  • Stored procedure: command.CommandType = CommandType.StoredProcedure;
  • Entire table: command.CommandType = CommandType.TableDirect;

Examples of a SqlCommand object

Command new new = the SqlCommand the SqlCommand (); 
command.Connection = sqlCnt; // bind SqlConnection object

Or created directly from SqlConnection

SqlCommand command = sqlCnt.CreateCommand();     

Common methods:

  • command.ExecuteNonQuery (): returns the affected function, such as add, delete, change operation;
  • command.ExecuteScalar (): execute the query and returns the results of the first line of the first column;
  • command.ExecuteReader (): returns a data stream (the SqlDataReader object).

Common Operations

① execute SQL
SqlCommand cmd = conn.CreateCommand (); // create a SqlCommand object 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "from the SELECT * Products's @ID ="; // SQL statement 
cmd.Parameters.Add ( "@ ID" , SqlDbType.Int); 
. cmd.Parameters [ "@ ID"] = the Value. 1; // parameters sql statement to assign
② call a stored procedure
SqlCommand cmd = conn.CreateCommand();                      
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "存储过程名";
③ the entire table
SqlCommand cmd = conn.CreateCommand();    
cmd.CommandType = System.Data.CommandType.TableDirect;
cmd.CommandText = "表名"

5, SqlDataReader Object

Namespace: System.Data.SqlClient.SqlDataReader;

SqlDataReader object provides functions to read only one-way data, unidirectional: only data sequentially read next; read-only: the DataReader data is read-only, can not be modified; data corresponding to DataSet can read and modify any .

It has a very important method is the Read (), the return value is a Boolean value, is to advance to the next data, a section of the return data is executed, when the jump is false boolean value is true. Such as

= New new of the SqlCommand the Command of the SqlCommand (); 
command.Connection = sqlCnt; 
command.CommandType = CommandType.Text; 
command.CommandText = "* from the Select the Users"; 
SqlDataReader = Command.ExecuteReader Reader (); // execute SQL, returns a " stream " 
the while (reader.Read ()) 
{ 
    Console.Write (Reader [" username "]); // print out each user's user name 
}

6, DataSet objects

6.1 SqlDataAdapter;

Namespace: System.Data.SqlClient.SqlDataAdapter;

Is a bridge between SqlCommand SqlDataAdapter and DataSet, SqlDataAdapter object instantiated:

The SqlConnection = new new sqlCnt the SqlConnection (connectString); 
sqlCnt.Open (); 

// creation of the SqlCommand 
of the SqlCommand the MySqlCommand = new new of the SqlCommand (); 
mySqlCommand.CommandType = CommandType.Text; 
mySqlCommand.CommandText = "from the SELECT * Product"; 
mySqlCommand.Connection = sqlCnt; 

// create a SqlDataAdapter 
SqlDataAdapter myDataAdapter = new new SqlDataAdapter (); 
myDataAdapter.SelectCommand = the MySqlCommand; // to be executed for the SqlDataAdapter object bound SqlCommand object

SQL can be simplified as above

The SqlConnection = new new sqlCnt the SqlConnection (connectString); 
sqlCnt.Open (); 
// hide the definition SqlCommand objects while hiding bound SqlCommand object and SqlDataAdapter object 
SqlDataAdapter myDataAdapter = new SqlDataAdapter ( "select * from product", sqlCnt) ;
Properties and Methods
  • myDataAdapter.SelectCommand properties: SqlCommand variable package Select statement;
  • myDataAdapter.InsertCommand properties: SqlCommand variable package Insert statement;
  • myDataAdapter.UpdateCommand properties: SqlCommand variable package Update statement;
  • myDataAdapter.DeleteCommand properties: SqlCommand variable package Delete statements.
  • myDataAdapter.fill (): The execution results are filled in the Dataset, hides open SqlConnection and perform SQL operations.

6.2 SqlCommandBuilder;

Namespace: System.Data.SqlClient.SqlCommandBuilder.

The operation of the DataSet (change, add, delete) only in local modifications, to submit to the "database" is required SqlCommandBuilder object. After the client for editing the data, the overall update data. Specific usage is as follows:

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder (myDataAdapter) ; // function to myDataAdapter given SqlCommandBuilder 
myDataAdapter.Update (myDataSet, "table"); // DataSet submitted after the changes to the database, the second parameter is the name of a stored table in the DataSet, not a real database table names (both the same in most cases).

6.3 DataSet

Namespace: System.Data.DataSet.

Data collection, local micro database can store multiple tables.

The first step is to use DataSet SqlDataAdapter return data sets (Tables) filled Dataset object:

= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); 
the DataSet myDataSet the DataSet new new = (); // Create the DataSet 
myDataAdapter.Fill (myDataSet, "Product"); // returns the data set as a "table" fill the DataSet, database table names may be different from the real table does not affect the subsequent add, delete, change operations and the like
① access data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

DataTable myTable = myDataSet.Tables["product"];
foreach (DataRow myRow in myTable.Rows) {
    foreach (DataColumn myColumn in myTable.Columns) {
        Console.WriteLine(myRow[myColumn]);	//遍历表中的每个单元格
    }
}
② modify data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

// 修改DataSet
DataTable myTable = myDataSet.Tables["product"];
foreach (DataRow myRow in myTable.Rows) {
    myRow["name"] = myRow["name"] + "商品";
}

// 将DataSet的修改提交至“数据库”
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Update(myDataSet, "product");

Note:. "For does not return any key column information SelectCommand, UpdateCommand does not support dynamic SQL generation" must be defined in a primary key modify, and delete tables product, select the field must also contain a primary key, otherwise it will prompt an error

③ add a line
= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); 
the DataSet myDataSet the DataSet new new = (); 
myDataAdapter.Fill (myDataSet, "Product"); 
the DataTable myTable myDataSet.Tables = [ "Product"]; 

// Add line 
the DataRow myRow myTable.NewRow = (); 
myRow [ "name"] = "Giant"; 
myRow [ ". price"] = 13.2; 
// myRow [ "ID"] = 100; if the ID is "Auto growth", this at may not be provided, even if the setting is also invalid 
myTable.Rows.Add (myRow); 

// modified DataSet submitted to "database" 
the SqlCommandBuilder MySqlCommandBuilder the SqlCommandBuilder new new = (myDataAdapter); 
myDataAdapter.Update (myDataSet, "Product");
④ delete a row
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

// 删除第一行
DataTable myTable = myDataSet.Tables["product"];
myTable.Rows[0].Delete();

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Update(myDataSet, "product");
Attributes
  • Tables: obtaining a set of tables contained in the DataSet.
  • Relations: get used to link the table and allows you to browse the collection from the parent table to the child table relationships.
  • HasEroors: Indicates whether the value has been initialized DataSet object.
method
  • Clear Clear all DataSet object data for all tables.
  • Clone DataSet object copied to another structure DataSet object, the copy includes all structures, relationships and constraints, but does not contain any data.
  • Copy The data structures and objects to another DataSet DataSet object. Exactly the same two DataSet objects.
  • CreateDataReader DataTableReader returns with a result set for each DataTable object, the display order of the same order Tables collection of tables.
  • Dispose Releases resources DataSet object occupies.
  • Reset will initialize the DataSet object.

7, free up resources

After use of resources should be released promptly and close the connection, as follows:

myDataSet.Dispose (); // release DataSet object 
myDataAdapter.Dispose (); // release SqlDataAdapter object 
myDataReader.Dispose (); // release the SqlDataReader 
sqlCnt.Close (); // close the connection 
sqlCnt.Dispose (); // release the database connection object

 

Links: Beijing Aerospace Control Technology Co., Ltd. in Switzerland

Guess you like

Origin www.cnblogs.com/harrychinese/p/csharp_sql.html