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

SqlCommand command = new 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 = "select * from products = @ID";   //sql语句
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters [ "@ ID"] Value = 1;. // Parameter sql statement to assign
② call a stored procedure
SqlCommand cmd = conn.CreateCommand();                      
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "stored procedure name";
③ 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 to provide a read-only-way function 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

SqlCommand command = new SqlCommand();
command.Connection = sqlCnt;
command.CommandType = CommandType.Text;
command.CommandText = "Select * from Users";
SqlDataReader reader = command.ExecuteReader (); // execute SQL, returns a "flow"
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:

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

// create a SqlCommand
SqlCommand mySqlCommand = new SqlCommand();
mySqlCommand.CommandType = CommandType.Text;
mySqlCommand.CommandText = "select * from product";
mySqlCommand.Connection = sqlCnt;

// Create a SqlDataAdapter
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
SqlCommand object // to SqlDataAdapter object is bound to be executed; myDataAdapter.SelectCommand = mySqlCommand

SQL can be simplified as above

SqlConnection sqlCnt = new 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); // SqlCommandBuilder function of imparting myDataAdapter
myDataAdapter.Update (myDataSet, "table"); // DataSet submitted after the changes to the database, the second parameter is stored in the DataSet table name, 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:

SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();		// 创建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]); // table traversing each cell
    }
}
② modify data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");

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

// modified DataSet is submitted to the "Database"
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
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "product");
DataTable myTable = myDataSet.Tables["product"];

// add a line
DataRow myRow = myTable.NewRow();
myRow [ "name"] = "Giant";
myRow["price"] = 13.2;
// myRow [ "id"] = 100; id If "Auto growth" here may not be provided, even if the settings are invalid
myTable.Rows.Add(myRow);

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

// delete the first line
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 the DataSet object
myDataAdapter.Dispose (); // release SqlDataAdapter object
myDataReader.Dispose (); // release SqlDataReader object
sqlCnt.Close (); // close the connection
sqlCnt.Dispose (); // release the database connection object

 

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

Reproduced in: https: //www.cnblogs.com/rainman/archive/2012/03/13/2393975.html

Guess you like

Origin blog.csdn.net/weixin_34232363/article/details/93561304