C#一般鏈接sqlserver數據庫,當然也會鏈接oracle。C#和MYSQL搭配貌似不多見哦
下面說說方法。
1、下載鏈接庫文件,MySql.Data.dll
2、工程引用文件,並在類文件中應用using
using MySql.Data; using MySql.Data.MySqlClient;
3、下來其他就和sqlserver差不多了。
4、配置文件中的鏈接字符串和鏈接變量
<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"];
5、定義兩個常用的數據庫類方法,操作數據庫和查詢
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);
} }
6、使用方法,顯示數據
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 = "數據庫連接失敗"; }
}
7、使用方法,對數據進行增刪改
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數據庫