.net開發中MysqlHelper幫助類
阿新 • • 發佈:2019-02-05
web.config配置
<add key="version" value="v1.2.1" />
<add key="MySQLconn" value="server=;database=moonshinetest;user id=root;password=;CharacterSet=gb2312;" />
//資料庫連線字串(web.config來配置),可以動態更改connectionString支援多資料庫.
// public static string connectionString = ConfigurationManager.ConnectionStrings["ConnDB"].ConnectionString;
public static string connectionString = ConfigurationManager.AppSettings["MySQLconn"];
////儲存過程
public static DataTable ExecuteDataTableCommand(string CommandText)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandText;
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds" );
cmd.Parameters.Clear();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
}
}
#region ExecuteNonQuery
//執行SQL語句,返回影響的記錄數
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteNonQuery(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteNonQuery(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = 1;
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
//執行多條SQL語句,實現資料庫事務。
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static bool ExecuteNoQueryTran(List<String> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
PrepareCommand(cmd, conn, tx, strsql, null);
cmd.ExecuteNonQuery();
}
}
cmd.ExecuteNonQuery();
tx.Commit();
return true;
}
catch
{
tx.Rollback();
return false;
}
}
}
#endregion ExecuteNonQuery
#region ExecuteScalar
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object ExecuteScalar(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object ExecuteScalar(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
#endregion ExecuteScalar
#region ExecuteReader
/// <summary>
/// 執行查詢語句,返回MySqlDataReader ( 注意:呼叫該方法後,一定要對MySqlDataReader進行Close )
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string strSQL)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
/// <summary>
/// 執行查詢語句,返回MySqlDataReader ( 注意:呼叫該方法後,一定要對MySqlDataReader進行Close )
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// }
}
#endregion ExecuteReader
#region ExecuteDataTable
/// <summary>
/// 執行查詢語句,返回DataTable
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataTable</returns>
public static DataTable ExecuteDataTable(string SQLString)
{
connectionString = ConfigurationManager.AppSettings["MySQLconn"];
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
connection.Close();
return ds.Tables[0];
}
}
#region ExecuteDataTable
/// <summary>
/// 執行查詢語句,返回DataTable
/// </summary>
/// <param name="db">資料庫型別(Nozzle,Feeder,Head)</param>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataTable</returns>
public static DataTable ExecuteDataTable(string db, string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
}
#endregion ExecuteDataTable
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataTable</returns>
public static DataTable ExecuteDataTable(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
}
}
//獲取起始頁碼和結束頁碼
public static DataTable ExecuteDataTable(string cmdText, int startResord, int maxRecord)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(cmdText, connection);
command.Fill(ds, startResord, maxRecord, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
}
#endregion ExecuteDataTable
/// <summary>
/// 獲取分頁資料 在不用儲存過程情況下
/// </summary>
/// <param name="recordCount">總記錄條數</param>
/// <param name="selectList">選擇的列逗號隔開,支援top num</param>
/// <param name="tableName">表名字</param>
/// <param name="whereStr">條件字元 必須前加 and</param>
/// <param name="orderExpression">排序 例如 ID</param>
/// <param name="pageIdex">當前索引頁</param>
/// <param name="pageSize">每頁記錄數</param>
/// <returns></returns>
public static DataTable getPager(out int recordCount, string selectList, string tableName, string whereStr, string orderExpression, int pageIdex, int pageSize)
{
int rows = 0;
DataTable dt = new DataTable();
MatchCollection matchs = Regex.Matches(selectList, @"top\s+\d{1,}", RegexOptions.IgnoreCase);//含有top
string sqlStr = sqlStr = string.Format("select {0} from {1} where 1=1 {2}", selectList, tableName, whereStr);
if (!string.IsNullOrEmpty(orderExpression)) { sqlStr += string.Format(" Order by {0}", orderExpression); }
if (matchs.Count > 0) //含有top的時候
{
DataTable dtTemp = ExecuteDataTable(sqlStr);
rows = dtTemp.Rows.Count;
}
else //不含有top的時候
{
string sqlCount = string.Format("select count(*) from {0} where 1=1 {1} ", tableName, whereStr);
//獲取行數
object obj = ExecuteScalar(sqlCount);
if (obj != null)
{
rows = Convert.ToInt32(obj);
}
}
dt = ExecuteDataTable(sqlStr, (pageIdex - 1) * pageSize, pageSize);
recordCount = rows;
return dt;
}
#region 建立command
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, 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 = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (MySqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
#endregion 建立command