C # Connect to the database MySQL and execute the query command

Source: Internet
Author: User

First, download the MySql.Data.dll and place it under Dubug in your project directory.

Next, right click on your project name and select "Add Reference" to add MySql.Data.dll to the project

Finally, enter the using MySql.Data.MySqlClient in the code page; You can then use this class library to establish a connection.

To establish the connection code:

Mysqlconnection Sqlcon = new Mysqlconnection ("database= database name; The IP address of the data source= server; User id= username; password= user password ");

Or:

Mysqlconnection Sqlcon = new Mysqlconnection ("server= server IP address; user id= username; password= user password; database= database name");

Or:
String M_str_sqlcon = "server= server IP address; User id= username; password= user password; database= database name "; According to your own settings
Mysqlconnection Sqlcon = new Mysqlconnection (M_str_sqlcon);

server= server IP address; User id= username; password= user password; database= database name, these order can be swapped, as long as the alignment of each string and identity Fus.

To set the query command code:

Set query commands
Mysqlcommand cmd = new Mysqlcommand ("SELECT * from MyFunc where TITLE like '%p% '", Sqlcon);
Query Result Reader
Mysqldatareader reader = null;

Get the query result code:

Try
{
Open connection
Sqlcon.open ();
Executes the query and returns the result to the reader
reader = cmd. ExecuteReader ();
while (reader. Read ())
{
Result_textbox.text + = "id=" + reader[0]. ToString () + ", title=" + reader[1]. ToString () + ", keyword=" +
READER[2]. ToString () + ", content=" + reader[3]. ToString () + ".";
}

}
catch (Exception ex) {}
Finally
{
Reader. Close ();
Sqlcon.close ();
}

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.