[C#]C#连接MySQL方法
程序员文章站
2022-06-12 17:13:15
...
1.需要添加引用:MySql.Data.dll,可以网上搜索下载;
2.SqlHelper写法:
此处connStr写死了,实际上应该写在配置文件中,再读取;写法如下:
public static readonly string connStr = "Server=192.168.0.1;Port=2222;Database=TEST;Uid=root;Pwd=123";
public static int ExecuteNonQuery(string sql, params MySqlParameter[] parameters)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
}
public static Object ExecuteScalar(string sql, params MySqlParameter[] parameters)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
}
}
public static DataTable ExecuteTable(string sql, params MySqlParameter[] parameters)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
DataSet dataSet = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}
}
public static DataSet ExecuteDataSet(string sql, params MySqlParameter[] parameters)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
DataSet dataSet = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataSet);
return dataSet;
}
}
}
上一篇: C#通过 WURFL 获取设备信息
下一篇: C#获取设备信息