先下載下傳和安裝MySQLDriverCS
http://sourceforge.net/projects/mysqldrivercs/
在安裝檔案夾下面找到MySQLDriver.dll,然後将MySQLDriver.dll添加引用到項目中
應用程式配置檔案:
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="server" connectionString="localhost"></add>
<add name="database" connectionString="housing"></add>
<add name="login" connectionString="root"></add>
<add name="password" connectionString="root"></add>
</connectionStrings>
</configuration>
SqlHelper.cs内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MySQLDriverCS;
using System.Data;
namespace Demo
{
class SqlHelper
{
private static string server = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private static string database = ConfigurationManager.ConnectionStrings["database"].ConnectionString;
private static string login = ConfigurationManager.ConnectionStrings["login"].ConnectionString;
private static string password = ConfigurationManager.ConnectionStrings["password"].ConnectionString;
public static int ExecuteNoQuery(String sql,MySQLParameter[] parameters)
{
using (MySQLConnection conn = new MySQLConnection(new MySQLConnectionString(server, database, login, password).AsString))
{
conn.Open();
//防止亂碼
MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
commn.ExecuteNonQuery();
//連接配接語句和SQL
MySQLCommand cmd = new MySQLCommand(sql, conn);
//添加參數
cmd.Parameters.AddRange( parameters);
//傳回執行結果
return cmd.ExecuteNonQuery();
}
}
public static object ExecuteScalar(String sql, MySQLParameter[] parameters)
cmd.Parameters.AddRange(parameters);
//較少的時候
public static DataTable ExecuteReaderEx(String sql, MySQLParameter[] parameters)
MySQLDataAdapter mda = new MySQLDataAdapter(cmd);
//查詢出的資料是存在DataTable中的,DataTable可以了解成為一個虛拟的表,DataTable中的一行為一條記錄,一列為一個資料庫字段
DataTable dt = new DataTable();
mda.Fill(dt);
return dt;
public static DataSet ExecuteReaderEx2(String sql, MySQLParameter[] parameters)
DataSet ds = new DataSet();
mda.Fill(ds);
return ds;
}
}
使用示例:
//sql語句
string sql = "update tbl_sysuser set isActived=@isActived where id=@id";
int number = SqlHelper.ExecuteNoQuery(sql, new MySQLParameter[]
{
new MySQLParameter("@isActived", "YES"),
new MySQLParameter("@id", 2)
});
Console.WriteLine("受影響的行數:" + number);
————————————————
版權聲明:本文為CSDN部落客「明明如月學長」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:
https://blog.csdn.net/w605283073/article/details/43678149