C # Summary of database development skills

Source: Internet
Author: User

1. Use SqlConnection to connect to SQL Server

1. Add a namespace

Using System. Data. SqlClient;

2. Connect to the database

SqlConnection myConnection = new SqlConnection ();
MyConnection. ConnectionString = "user id = sa; password = sinofindb; initial catalog = test; data source = 127.0.0.1; Connect Timeout = 30 ";
MyConnection. Open ();

Improved (more general) methods:

String MySqlConnection = "user id = sa; password = sinofindb; Database = test; data source = 127.0.0.1; Connect Timeout = 30 ";
SqlConnection myConnection = new SqlConnection (MySqlConnection );
MyConnection. Open ();

II. Use OleDbConnection to connect

1. Add a namespace

Using System. Data. OleDb;

2. Connect to SQL server

String MySqlConnection = "Provider = SQLOLEDB; Data Source = localhost; Initial Catalog = test; Integrated Security = SSPI ;";

SqlConnection myConnection = new SqlConnection (MySqlConnection );
MyConnection. Open ();

3. Connect to Access (strings can be obtained by creating a. udl file)

String MySqlConnection = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = c: \ db2000.mdb;

Persist Security Info = False;

4. Connect to Oracle (you can also connect through OracleConnection)

String MySqlConnection = "Provider = MSDAORA; Data Source = db; user id = sa; password = sinofindb ";

 

3. Create a Command object

1. SqlCommand Constructor

① Initialize a new instance of the SqlCommand class. Public SqlCommand ();

SqlCommand myCommand = new SqlCommand ();

 

② Initialize a new instance of the SqlCommand class with query text. Public SqlCommand (string );

String mySelectQuery = "SELECT * FROM mindata ";
SqlCommand myCommand = new SqlCommand (mySelectQuery );
③ Initialize the SqlCommand class instance with query text and SqlConnection.

Public SqlCommand (string, SqlConnection );

String mySelectQuery = "SELECT * FROM mindata ";
String myConnectString = "user id = sa; password =; database = test; server = mySQLServer ";
SqlConnection myConnection = new SqlConnection (myConnectString );
SqlCommand myCommand = new SqlCommand (mySelectQuery, myConnection );
 

④ Initialize the SqlCommand class instance with query text, SqlConnection, and Transaction.

Public SqlCommand (string, SqlConnection, SqlTransaction );

SqlTransaction myTrans = myConnection. BeginTransaction ();
String mySelectQuery = "SELECT * FROM mindata ";
String myConnectString = "user id = sa; password =; database = test; server = mySQLServer ";
SqlConnection myConnection = new SqlConnection (myConnectString );
SqlCommand myCommand = new SqlCommand (mySelectQuery, myConnection, myTrans );
 

2. Establish an association between SqlCommand and SqlConnection.

MyCommand. Connection = myConnection;

Or: SqlCommand myCommand = myConnection. CreateCommand;

 

3. Set the query text of SqlCommand.

MyCommand. CommandText = "SELECT * FROM mindata ";

Or 2nd types of structures: SqlCommand myCommand = new SqlCommand (mySelectQuery );

The SqlCommand object provides two query strings. Each query string Accesses Different tables and returns different result sets.

The two query statements are separated by semicolons.

 

4. Run the command.

ExecuteReader
Returns one or more rows.
 
ExecuteNonQuery
Execute a Transact-SQL statement on the Connection and return the affected number of rows (int)
 
ExecuteScalar
Returns a single value (such as an aggregate value). returns the first column of the first row of the result set. Ignore extra columns or rows
 
ExecuteXmlReader
Send CommandText to Connection and generate an XmlReader object.

SqlDataReader myReader = myCommand. ExecuteReader ();

Or SqlDataReader myReader = myCommand. ExecuteReader (CommandBehavior. CloseConnection );

While (myReader. Read () // Read data cyclically
{
Console. WriteLine (myReader. GetString (0); // obtain the value in the string format of the specified Column
Console. WriteLine (myReader. GetValue(1); // obtain the value of a specified column in the local format
}
 

CommandText = "select count (*) as NumberOfRegions from region ";
Int count = (int) myCommand. ExecuteScalar ();

 

The use of OleDbCommand objects.

4. Use of DataReader

 

1. traverse the result set

While (myReader. Read ())

Console. WriteLine ("\ t {0} \ t {1}", myReader. GetInt32 (0), myReader. GetString (1 ));

MyReader. Close ();

 

2. Use the ordinal index.

While (myReader. Read ())

Console. WriteLine ("\ t {0} \ t {1}", myReader [0]. ToString (), myReader [1]. ToString ());

MyReader. Close ();

 

3. Use the column name indexer.

While (myReader. Read ())

Console. WriteLine ("\ t {0} \ t {1}", myReader ["code]. ToString (), myReader [" name "]. ToString ());

MyReader. Close ();

 

4. Use the type accessors.

Public char GetChar (int I); returns a single string value of the specified column.

Public DateTime GetDateTime (int I); get the value in the DateTime format of the specified Column

Public short GetInt16 (int I); get the 16-bit signed integer form of the specified column [C #]

Public string GetString (int I); get the value in the string format of the specified Column

 

5. Obtain the column information.

MyReader. FieldCount gets the number of columns in the current row

MyReader. GetFieldType (serial number) is the Type of the object's data Type.

MyReader. GetDataTypeName (serial number) Get the name of the source data type

MyReader. GetName (serial number) to get the name of the specified Column

MyReader. GetOrdinal (sequence number) obtains the sequence number of a given column name.

 

6. Obtain the data table information.

MyReader. GetSchemaTable () returns a DataTable

 

7. Operate multiple result sets.

MyReader. NextResult () enables the data reader to move forward to the next result set

Do

{

While (myReader. Read ())

Console. WriteLine ("\ t {0} \ t {1}", myReader. GetInt32 (0), myReader. GetString (1 ));

}

While (myReader. NextResult ());

 

5. DataAdapter

 

1. Create SqlDataAdapter

Initialize a new instance of the SqlDataAdapter class.

Public SqlDataAdapter ();

 

Use the specified SqlCommand as the SelectCommand attribute to initialize a new instance of the SqlDataAdapter class.

Public SqlDataAdapter (SqlCommand );

 

Use the selectcommand string and SqlConnection object to initialize a new instance of the SqlDataAdapter class.

Public SqlDataAdapter (string, SqlConnection );

 

Use the selectcommand string and a connection string to initialize a new instance of the SqlDataAdapter class.

Public SqlDataAdapter (string, string );

 

2. Create an association between DataAdapter, SqlConnection, and SqlCommand.

1. DataAdapter is created when constructing Parameters

2. SqlDataAdapter adapter = new SqlDataAdapter ();

Adapter. SelectCommand = new SqlCommand (query, conn );

 

3. DataAdapter. Fill () method.

Add or refresh rows in DataSet to match the rows in the data source with the DataSet name, and create a DataTable named "Table.

Public override int Fill (DataSet );

 

Add or refresh rows in DataSet to match the rows in the data source that uses the DataSet and able names.

Public int Fill (DataSet, string );

 

Add or refresh rows in the specified range of DataSet to match the rows in the data source using the DataSet and DataTable names.

Public int Fill (DataSet, int, int, string );

 

Add or refresh rows in DataTable to match rows in the data source that uses the DataTable name.

Public int Fill (DataTable );

 

Add or refresh rows in the DataTable to match the rows in the data source that uses the specified DataTable and IDataReader names.

Protected virtual int Fill (DataTable, IDataReader );

 

Add or refresh rows in the DataTable to match rows in the data source that uses the DataTable name, specified SQL SELECT statement, and CommandBehavior.

Protected virtual int Fill (DataTable, IDbCommand, CommandBehavior );

 

6. DataTable class

VII. DataColumn class

8. DataRow class

9. DataSet class
1. Create a DataSet object

Initializes a new instance of the DataSet class.

Public DataSet ();

 

Initialize a new instance of the DataSet class with the given name.

Public DataSet (string );
 

2. Fill DataSet with DataAdapter

DataSet myds = new DataSet ();

Adapter. fill (myds)

Adapter. fill (myds, "table name"); fill DataSet with a table.

10. DataTableCollection class. Indicates the set of DataSet tables.

DataTableCollection dtc = ds. Tables;

DataTable table = dtc ["table name"];

 

String strExpr = "id> 5 ";

String strSort = "name DESC ";

DataRow [] foundRows = customerTable. Select (strExpr, strSort ,);

 

Dynamic Filtering and sorting.

DataTable. Select () method: Get the array of the DataRow object,

① Obtain the array of all DataRow objects.

Public DataRow [] Select ();

 

② Obtain the array of all DataRow objects that match the filtering conditions in the primary key order (if no primary key exists.

Public DataRow [] Select (string );

 

③ Obtain the array of all DataRow objects in the specified sorting order that matches the filtering conditions.

Public DataRow [] Select (string, string );

 

④ Obtain the array of all DataRow objects that match the filters and specified states in the sorting order.

Public DataRow [] Select (string, string, DataViewRowState );

 

11. DataView class: a dynamic view of DataTable content.

1. Create an object

Initialize a new instance of the DataView class.

Public DataView ();

 

Use the specified DataTable to initialize a new instance of the DataView class.

Public DataView (DataTable );

 

Use the specified able, RowFilter, Sort, and DataViewRowState to initialize a new instance of the DataView class.

Public DataView (DataTable, string, string, DataViewRowState );

 

DataView myview = new DataView (ds. Tables ["Suppliers"],

"Id> 5 ",

"Name DESC ",

DataViewRowState. CurrentRows );

 

 

2. Get the row data of DataView.

Foreach (DataRowView myrowview in myview)

{

For (int I = 0; I <myview. Table. Columns. Count; I ++)

Console. Write (myrowview + "\ t ");

Console. WriteLine ();

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.