C#通常連接sqlserver數據庫,固然也會連接oracle。C#和MYSQL搭配貌似很少見哦mysql
下面說說方法。sql
一、下載連接庫文件,MySql.Data.dll數據庫
MySql.Data.raroracle
二、工程引用文件,並在類文件中應用usingapp
using MySql.Data; using MySql.Data.MySqlClient;sqlserver
三、下來其餘就和sqlserver差很少了。this
四、配置文件中的連接字符串和連接變量server
<appSettings> <add key="conn" value="Database='tdm';Data Source='localhost';User Id='root';Password='root';charset='utf8';pooling=true"/> </appSettings>對象
public static string Conn = System.Configuration.ConfigurationManager.AppSettings["conn"];字符串
五、定義兩個經常使用的數據庫類方法,操做數據庫和查詢
public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters) {
MySqlCommand cmd = new MySqlCommand();
using (MySqlConnection conn = new MySqlConnection(Conn))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
public static DataSet GetDataSet(CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
{
//建立一個MySqlCommand對象
MySqlCommand cmd = new MySqlCommand();
//建立一個MySqlConnection對象
MySqlConnection conn = new MySqlConnection(Conn);
try {
//調用 PrepareCommand 方法,對 MySqlCommand 對象設置參數
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
//調用 MySqlCommand 的 ExecuteReader 方法
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
adapter.Fill(ds);
//清除參數
cmd.Parameters.Clear();
conn.Close();
return ds;
}
catch (Exception e ) { throw e; } }
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms) {
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null) {
foreach (MySqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
} }
六、使用方法,顯示數據
private void button2_Click(object sender, EventArgs e) {
string sql="select * from deviceinfo";
try {
dataGridView1.DataSource = MySqlHelper.GetDataSet( CommandType.Text,sql,null).Tables[0]; } catch (Exception) {
this.Text = "數據庫鏈接失敗"; }
}
七、使用方法,對數據進行增刪改
try {
string sql = "select * from deviceinfo";
DataTable dt = MySqlHelper.GetDataSet(CommandType.Text, sql, null).Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
sql = "update deviceinfo set devicestatus=" + fsMakeStatuts().ToString() + " where deviceid='" + dt.Rows[i]["deviceid"].ToString() + "'"; MySqlHelper.ExecuteNonQuery(CommandType.Text, sql, null);
}
} catch (Exception) {
this.Text = "err"; }
原文連接:C#怎樣連接mysql數據庫