C # connect to the MYSQL database, including adding, deleting, querying, and modifying C # connect to the MYSQL database, including adding, deleting, querying, modifying, and modifying!
Public class DBLINK
{
Public MySqlConnection GetConn ()
{
MySqlConnection mysqlconn = new MySqlConnection ("server = localhost; pwd = 123; user = root; database = pfms; charset = 'gb2312 '"); // 1, server 2 Mysql password 3 mysql username 4 database name 5 database encoding method
Return mysqlconn;
}
}
Public class SQLEXQ: DBLINK
{
/// Query operation
Public DataTable Select (string SQL)
{
MySqlConnection mysqlconn = null;
MySqlDataAdapter sda = null;
DataTable dt = null;
Try
{
Mysqlconn = base. GetConn ();
Sda = new MySqlDataAdapter (SQL, mysqlconn );
Dt = new DataTable ();
Sda. Fill (dt );
Return dt;
}
Catch (Exception)
{
Throw;
}
}
/// Add operation
Public int Add (string SQL)
{
MySqlConnection conn = null;
MySqlCommand cmd = null;
Try
{
Conn = base. GetConn ();
Conn. Open ();
Cmd = new MySqlCommand (SQL, conn );
Int I = cmd. ExecuteNonQuery ();
Conn. Close ();
Return I;
}
Catch (Exception)
{
Throw;
}
}
// Modify
Public int Change (string SQL)
{
MySqlConnection conn = null;
MySqlCommand cmd = null;
Try
{
Conn = base. GetConn ();
Conn. Open ();
Cmd = new MySqlCommand (SQL, conn );
Int I = cmd. ExecuteNonQuery ();
Conn. Close ();
Return I;
}
Catch (Exception)
{
Throw;
}
}
// Delete
Public int Delete (string SQL)
{
MySqlConnection conn = null;
MySqlCommand cmd = null;
Try
{
Conn = base. GetConn ();
Conn. Open ();
Cmd = new MySqlCommand (SQL, conn );
Int I = cmd. ExecuteNonQuery ();
Conn. Close ();
Return I;
}
Catch (Exception)
{
Throw;
}
}
}
}
Usage:
// Query
String sql1 = "select max (inumber) + 1 as num from income"; // query SQL statements
DataTable dt = mysql. Select (sql1); // put it in the data table
If (dt. Rows. Count> 0) // whether data exists
{
For (int I = 0; I <dt. Rows. Count; I ++)
{
Ia. textBox_bh.Text = dt. Rows [I] ["num"]. ToString (); // display in the edit box
}
}
For other similar statements, you only need to change the SQL statement! For is a specific operation to read, store, delete, or modify the data!
By the way, I use MYSQL. data to connect to the database, so I need to use using MySql. Data. MySqlClient; // import the MySql package! You also need to import MySql. Data. dll to the application of the C # Project! Controls; http://download.csdn.net/my