using System.Configuration;
using MySql.Data; public class MySqlHelp
{
//链接字符串
private static string connection = ConfigurationManager.ConnectionStrings["db"].ConnectionString; // 执行insert、delete、update的方法
public static int ExcuteNonQuery(string sql, params DbParameter[] parameter)
{
using (MySqlConnection con = new MySqlConnection(connection))
{
if (con.State == ConnectionState.Closed) con.Open(); using (MySqlCommand cmd = new MySqlCommand(sql,con))
{
if (parameter != null)
{
cmd.Parameters.AddRange(parameter);
} return cmd.ExecuteNonQuery();
}
}
} // 执行sql语句,返回单个值。
public static object ExecuteScalar(string sql, params DbParameter[] parameters)
{
using (MySqlConnection con = new MySqlConnection(connection))
{
con.Open();
using (var cmd = new MySqlCommand(sql,con))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
return cmd.ExecuteScalar();
}
}
} //查询一个实例或列表
public static MySqlDataReader ExecuteReader(string sql, params DbParameter[] parameters)
{
MySqlConnection con = new MySqlConnection(connection);
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}

//查询集合
public static DataTable ExecuteDataTable(string sql, params DbParameter[] parameters)
{
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sql, connection);
if (parameters != null)
{
sqlAdapter.SelectCommand.Parameters.AddRange(parameters);
}
DataTable dt = new DataTable();
sqlAdapter.Fill(dt);
return dt;
}
}
05-04 05:29