Ado. NET Operation MySQL Database

Source: Internet
Author: User

Preface

Ado. NET includes 5 large objects, namely connection, Command, DataReader, DataSet, DataAdapter, using ADO to access the database has two steps: to establish a database connection, read or update data. There are two main ways of reading data: Command and DataReader, DataAdapter and DataSet.

Connection to MySQL database preparation 1. Download the free-install. zip link on the MySQL website as follows: Http://dev.mysql.com/downloads/connector/net/5.0.html,platform SELECT. Net      & Mono. 2. Unzip after download, unzip the file open V4.0 (the example in this blog is used in this version) 3. You can see some DLL files when you open them and add references to them in your project 4. The following example is the operation of the table Comment table in database test in MySQL. Step one: Establish a database connection 1. Define Global variables [CSharp]View PlainCopy
    1. To create a Command object
    2. private Mysqlcommand cmd = null;
    3. Create a Connection Connection object
    4. private Mysqlconnection conn = null;
2. Establishing a database connection [CSharp]View PlainCopy
    1. Database connection string
    2. String connstr = "Server=localhost;database =test;uid=root;pwd=1;charset=utf8";
    3. Establishing a database connection
    4. conn = new Mysqlconnection (CONNSTR);
Step two: Read Data 1.command and DataReader object read Data Description: The DataReader object provides a read-only forward pointer to the database retrieval data. DataReader is an abstract class that cannot be instantiated directly, so you need to create a command object before using it, and then create the DataReader object, which is read-only, so you cannot modify it. Process of reading data: ① Create connection ② Open connection ③ create command object ④ Execute command ExecuteReader () method ⑤ bind DataReader to Data Control ⑥ close Datareader⑦ Close The connection code shows: [CSharp]View PlainCopy
  1. Mysqldatareader reader = null;
  2. Try
  3. {
  4. Conn.    Open (); //② Opening a database connection
  5. cmd = new Mysqlcommand ("select * from comment", conn); //③ Creating a SqlCommand object using the specified SQL command and connection object
  6. reader = cmd. ExecuteReader (); //④ ExecuteReader () method to execute command
  7. //⑤ binding DataReader to a Data control
  8. DataTable dt = new DataTable ();
  9. Dt. Load (reader);
  10. Datagridview1.datasource = DT;
  11. }catch (Exception) {
  12. throw;
  13. }finally{
  14. //⑥ Close DataReader
  15. Reader. Close ();
  16. //⑦ Closing the connection
  17. Conn. Close ();
  18. }
[CSharp]View PlainCopy
2.DataSet and DataAdapter Object read Data Description: DataAdapter is the media between the dataset and the database, DataAdapter open a connection and execute the corresponding MySQL statement, the dataset is equivalent to a small database, You can store many tables, the dataset is a collection object, we can read the data in the dataset, and we can update the data in it. The process of reading data: ① Create a connection ② create a DataAdapter object ③ create a DataSet object ④ execute the DataAdapter object's fill () method ⑤ bind the table in the dataset to the code presentation in the Data control: [CSharp]View PlainCopy
  1. Try
  2. {
  3. string mysqltext = "select * from comment;";
  4. //Create a SqlDataAdapter object with the specified SQL command and connection object
  5. Mysqldataadapter MYSDA = new Mysqldataadapter (MYSQLTEXT, conn);
  6. DataSet ds = new DataSet (); //Create a DataSet object
  7. //Use the SqlDataAdapter Fill method to populate the DataSet Mysda.  Fill (ds, "comment");
  8. //bind a table in a dataset to a data control
  9. BindingSource BS;
  10. BS = new BindingSource ();
  11. Bs. DataSource = ds.   tables["comment"];
  12. Datagridview1.datasource = BS;
  13. }
  14. catch (Exception) {
  15. throw;
  16. }
[CSharp]View PlainCopy
Step three: Update data 1.command Object Update data Description: A transaction is a set of units of related tasks that either succeed or fail altogether. If they fail, all are rolled back, and the four properties (ACID) of the transaction are atomicity (atomicity), consistency (consistency), isolation (isolation), persistence (durability), respectively. Detailed information no longer repeat, do not know can Baidu a bit Oh! Code Show: [CSharp]View PlainCopy
  1. Database connection string
  2. String connstr = "Server=localhost;database =test;uid=root;pwd=1;charset=utf8";
  3. Establishing a database connection
  4. using (conn = new Mysqlconnection (CONNSTR))
  5. {
  6. Conn. Open ();
  7. //Start a transaction
  8. using (mysqltransaction transaction = conn. BeginTransaction ())
  9. {
  10. using (cmd=conn. CreateCommand ())
  11. {
  12. Try
  13. {
  14. Cmd.  Transaction = Transaction; //Specify a transaction for the command
  15. Cmd.commandtext = "insert into comment (quantity,comment) value (' 11 ', ' very good ');";
  16. Cmd. ExecuteNonQuery ();
  17. Cmd.commandtext = "insert into comment (quantity,comment) value (' 12 ', ' very good ');";
  18. Cmd. ExecuteNonQuery ();
  19. Transaction.commit (); //Transaction Submission
  20. }
  21. catch (Exception)
  22. {
  23. Transaction. Rollback (); //Transaction rollback
  24. }
  25. }
  26. }
  27. }
2.DataAdapter Object Update Data [CSharp]View PlainCopy
  1. <span style="FONT-SIZE:18PX;" >//Database connection string
  2. String connstr = "Server=localhost;database =test;uid=root;pwd=1;charset=utf8";
  3. //Establish database connection
  4. conn = new Mysqlconnection (CONNSTR);
  5. Try
  6. {
  7. //comment is the table name, quantity is the field name
  8. string mysqltext = "select * from comment;";
  9. Mysqldataadapter MYSDA = new Mysqldataadapter (MYSQLTEXT, conn);
  10. DataSet ds = new DataSet ();
  11. Mysda.  Fill (ds, "comment");
  12. //Bind Mysqldataadapter object, automatically generate command to update MySQL from DataSet
  13. Mysqlcommandbuilder cb = new Mysqlcommandbuilder (MYSDA);
  14. //Update data in DS
  15. Ds. tables["comment"].  rows[0]["Quantity"] = 111;
  16. //Update data in the database
  17. Mysda.  Update (ds, "comment");
  18. }
  19. catch (Exception)
  20. {
  21. throw;
  22. }</span>
Summary 1.DataReader object read data in the database can only read, and is read-only, can not be modified; The data read by the dataset and the DataAdapter object is readable and can be modified, and many tables can be stored in the dataset. 2.DataReader read the data before the need to manually write code to connect the database, that is Conn.Open (), after the completion of the query need to manually write code to close the database connection; the DataSet and the DataAdapter object do not need to manually write code to connect to the database before reading the data, it will automatically identify If the database connection is not open, it is turned on and automatically shuts down if it is not turned off.

Ado. NET Operation MySQL Database

Related Article

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.