数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.

SqlServer调用数据库

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient; namespace Dal
{
public static class DBHelper
{
public static string strCon = "Data Source=.;Initial Catalog=Week3;Integrated Security=True";
/// <summary>
/// 增删改
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="str">连接字符串</param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql)
{
//实例化连接对象
SqlConnection conn = new SqlConnection(strCon);
int result = ;
try
{
conn.Open();
//实例化命令对象
SqlCommand cmd = new SqlCommand(sql, conn);
//执行命令
result = cmd.ExecuteNonQuery();
}
catch (Exception)
{ throw;
}
finally
{
conn.Close();
}
return result;
}
/// <summary>
/// 获取表格
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="str">连接字符串</param>
/// <returns></returns>
public static DataTable GetDataTable(string sql)
{
//实例化连接对象
SqlConnection conn = new SqlConnection(strCon);
DataTable dt = new DataTable(); try
{
//实例化适配器
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt); }
catch (Exception)
{ throw;
}
return dt;
}
/// <summary>
///
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="str">连接字符串</param>
/// <returns></returns>
public static SqlDataReader GetDataReader(string sql)
{
//实例化连接对象
SqlConnection conn = new SqlConnection(strCon);
SqlDataReader sdr;
try
{
conn.Open();
//实例化命令对象
SqlCommand cmd = new SqlCommand(sql, conn);
sdr = cmd.ExecuteReader(); }
catch (Exception)
{ throw;
}
return sdr;
}
/// <summary>
/// 返回单行单列
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="str">连接字符串</param>
/// <returns></returns>
public static int ExecuteScalar(string sql)
{
//实例化连接对象
SqlConnection conn = new SqlConnection(strCon);
int result = ;
try
{
conn.Open();
//实例化命令对象
SqlCommand cmd = new SqlCommand(sql, conn);
result = Convert.ToInt32(cmd.ExecuteScalar());
}
catch (Exception)
{ throw;
}
finally
{ conn.Close();
}
return result;
} /// <summary>
/// 信息分页显示
/// </summary>
/// <returns></returns>
public static DataTable GetInfoByPage(int Pageindex, int PageSize)
{
string sql = string.Format(@"select top {0}* from(
select XinXi.*,ROW_NUMBER() over(order by XinXi.XinXiId) pid ,Type.Name from Type
inner join XinXi on Type.Id= XinXi.TypeId ) as temp
where temp.pid>{1}", PageSize, (Pageindex - ) * PageSize);
return DBHelper.GetDataTable(sql);
}
/// <summary>
/// 获取个数
/// </summary>
/// <returns></returns>
public static int GetCount()
{
string sql = "select count(XinXi.XinXiId) from Type inner join XinXi on Type.Id= XinXi.TypeId";
return DBHelper.ExecuteScalar(sql); }
}
}

SqlServer-DBHelper

SqlServer调用数据库存储过程

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web; namespace Unit07_Service
{
public class DBHelper
{ public static string connStr = "Data Source=.;Initial Catalog=DB_News;Integrated Security=True";
public static SqlConnection cnn = new SqlConnection(connStr); /// <summary>
/// 执行增删改的操作
/// </summary>
/// <param name="sql">sql命令</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(string sql)
{
Open();
SqlCommand command = new SqlCommand(sql, cnn);
int result = command.ExecuteNonQuery();
cnn.Close();
return result;
}
/// <summary>
/// 查询单个值
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql)
{
Open();
SqlCommand command = new SqlCommand(sql, cnn);
object result = command.ExecuteScalar();
cnn.Close();
return result;
}
/// <summary>
/// 返回数据表
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable GetDataTable(string sql)
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[];
}
/// <summary>
/// 返回DataReader对象,使用结束后,勿忘关闭DataReader与数据库
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static SqlDataReader GetDataReader(string sql)
{
Open();
SqlCommand command = new SqlCommand(sql, cnn);
return command.ExecuteReader();
}
/// <summary>
/// 打开数据库
/// </summary>
public static void Open()
{
if (cnn.State == ConnectionState.Broken || cnn.State == ConnectionState.Open)
{
cnn.Close();
}
cnn.Open();
} /// <summary>
/// 打开数据库
/// </summary>
public static void Close()
{
cnn.Close();
} /// <summary>
/// 使用存储过程查询数据结果
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public static DataTable GetDataTable(string procName, SqlParameter[] paras = null)
{
Open();
SqlCommand command = new SqlCommand(procName, cnn);
command.CommandType = CommandType.StoredProcedure; if (paras != null)
{
command.Parameters.AddRange(paras);
}
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
Close();
return ds.Tables[];
} /// <summary>
/// 使用存储过程执行增删改
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public static int ExecuteNonQuery(string procName, SqlParameter[] paras)
{
Open();
SqlCommand command = new SqlCommand(procName, cnn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddRange(paras); int result = command.ExecuteNonQuery();
Close(); return result; }
}
}

SqlServer-DBHelperProc

MySql调用数据库

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace Student_API.Controllers
{
/// <summary>
/// 数据访问抽象基础类
/// Copyright (C) 2004-2008 By LiTianPing
/// </summary>
public abstract class DbHelperMySQL
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = "server=127.0.0.1;user id=root;pwd=root;database=06a_exam";
public DbHelperMySQL()
{
} #region 公用方法
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return ;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <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 = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 是否存在(基于MySqlParameter)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
#endregion #region 执行简单SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(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;
}
}
}
} public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static int ExecuteSqlTran(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
{
int count = ;
for (int n = ; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > )
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return ;
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
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)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
} /// <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;
}
}
}
}
/// <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>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(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;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} #endregion #region 执行带参数的SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(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>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = ;
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(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;
}
}
}
} /// <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();
// } } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(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;
}
}
} 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 } }

MySql-DBHelper

MySql调用数据库存储过程

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace Student_Client
{
/// <summary>
/// 数据访问抽象基础类
/// Copyright (C) 2004-2008 By LiTianPing
/// </summary>
public abstract class DbHelperMySQL
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = "server=127.0.0.1;user id=root;pwd=root;database=06a_exam";
public DbHelperMySQL()
{
} #region 公用方法
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return ;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <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 = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 是否存在(基于MySqlParameter)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
#endregion #region 执行简单SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(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;
}
}
}
} public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static int ExecuteSqlTran(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
{
int count = ;
for (int n = ; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > )
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return ;
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
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)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
} /// <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;
}
}
}
}
/// <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>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(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;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} #endregion #region 执行带参数的SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(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>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = ;
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(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;
}
}
}
} /// <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();
// } } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(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;
}
}
} 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 #region 执行带参数的存储过程
/// <summary>
/// 执行带参数的存储过程
/// </summary>
/// <param name="SQLString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static object ExecuteProc(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{ PrepareCommand(cmd, connection, null, SQLString, cmdParms);
cmd.CommandType = CommandType.StoredProcedure;
int rows = cmd.ExecuteNonQuery();
Console.WriteLine("返回值为 " + cmdParms[].Value);
cmd.Parameters.Clear();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 存储过程查询DataTable
/// </summary>
/// <param name="SQLString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static DataTable QueryProc(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{ PrepareCommand(cmd, connection, null, SQLString, cmdParms);
cmd.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
cmd.Parameters.Clear();
return dt;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
#endregion } }

Mysql-DBHelperProc

C#工具:Ado.Net SqlServer数据库 MySql数据库的更多相关文章

  1. 在项目中迁移MS SQLServer到Mysql数据库,实现MySQL数据库的快速整合

    在开发项目的时候,往往碰到的不同的需求情况,兼容不同类型的数据库是我们项目以不变应万变的举措之一,在底层能够兼容多种数据库会使得我们开发不同类型的项目得心应手,如果配合快速的框架支持,那更是锦上添花的 ...

  2. ABP框架使用Mysql数据库,以及基于SQLServer创建Mysql数据库的架构和数据

    ABP默认的数据库是SQLServer,不过ABP框架底层是EF框架,因此也是很容易支持其他类型的数据库的,本篇随笔介绍在ABP框架使用Mysql数据库,以及基于SQLServer创建MySql数据库 ...

  3. Oracle、Db2、SqlServer、MySQL 数据库插入当前系统时间

    做易买网项目,由于对数据库插入系统时间不了解,常常遇到的问题: 1.java.sql.SQLException: ORA-01861: 文字与格式字符串不匹配.原因:由于获取系统时间类型不对,应为sy ...

  4. sqlyog管理关系型数据库mysql数据库之sqlyog的安装管理

    .关系型数据库 有库有表,有关系 非关系型数据库  存储对象.集 下面的所有演示截图都是基不超过SQLyog 11进行的. 1. 2.点击上图中的应用程序,进行安装. 安装sqlyog , 账户dd0 ...

  5. 数据库-mysql数据库和表操作

    一:数据库查询增加删除 1)mysql数据库查询:show databases MariaDB [mysql]> show databases; +--------------------+ | ...

  6. python数据库-MySQL数据库的增删改查基本操作(49)

    一.数据库基础 表 table:数据是保存在表内,保存在一个表内的数据,应该具有相同的数据格式 行:行用于记录数据 记录:行内的数据 列:列用于规定数据格式 字段:数据的某个列 主键:唯一地标识表中的 ...

  7. 我用工具怎么连接不上mysql数据库的? MySql access denied for user错误

    MySql access denied for user错误 方法/步骤   MySql远程连接时的"access denied for user **@**"错误,搞的我很头大, ...

  8. JDBC让java程序连上数据库(mysql数据库)

    一.小论异常: 其实JDK已经提供了一组API让java程序连上数据库,并执行SQL语句,其实说起来也蛮简单的,但是绝对是一个细致活,因为稍不留神,异常就铺天盖地的来了,下面说说这些异常吧(声明一下: ...

  9. python数据库-MySQL数据库高级查询操作(51)

    一.什么是关系? 1.分析:有这么一组数据关于学生的数据 学号.姓名.年龄.住址.成绩.学科.学科(语文.数学.英语) 我们应该怎么去设计储存这些数据呢? 2.先考虑第一范式:列不可在拆分原则 这里面 ...

随机推荐

  1. 浅谈URL跳转与Webview安全

    学习信息安全技术的过程中,用开阔的眼光看待安全问题会得到不同的结论. 在一次测试中我用Burpsuite搜索了关键词url找到了某处url,测试一下发现waf拦截了指向外域的请求,于是开始尝试绕过.第 ...

  2. 供应链金融&区块链应用

    现代管理教育对供应链的定义为“供应链是围绕核心企业,通过对商流,信息流,物流,资金流的控制,从采购原材料开始,制成中间产品以及最终产品,最后由销售网络把产品送到消费者手中的将供应商,制造商,分销商,零 ...

  3. mongodb副本集实现

    目录 1. 简单介绍 primary: secondary: arbiter: 2.系统环境设置: 3.安装mongodb 安装mongodb 增加配置文件: 添加启动脚本 3. 副本集实现: 1. ...

  4. Java代码规范与质量检测插件SonarLint

    1.  SonarLint SonarLint是一个代码质量检测插件,可以帮助我们检测出代码中的坏味道 下载与安装 在需要检测的单个文件或者单个项目上右键 --> Analyze --> ...

  5. java游戏开发杂谈 - 画布和画笔

    在Eclipse里,编写如下两个类: package game2; import java.awt.Color; import java.awt.Graphics; import javax.swin ...

  6. 学习笔记02(随便看看mybatis源码)

    两个很有名的持久层hibernate和mybatis应该很熟悉不过了,两者最大相同点是底层都是对jdbc的封装,最大的不同点是前者是自动生成sql语句,后者是需要我们在映射文件中写出sql. 其实从以 ...

  7. Scrapy爬虫遇到 ‘Forbidden by robots.txt’的问题

    今天在爬知乎精华时,出现了‘Forbidden by robots.txt’的问题 了解到到scrapy在爬取设定的url之前,它会先向服务器根目录请求一个txt文件,这个文件规定了爬取范围 scra ...

  8. centos 修改hostname

    centos修改主机名的正确方法 1 centos6下修改hostname [root@centos6 ~]$ hostname # 查看当前的hostnmae centos6.magedu.com ...

  9. DSAPI中TCP、UDP、HTTP的选择

    在DSAPI中,网络通讯主要有以下几种:1 [TCP] TCP服务端 TCP客户端 2 [UDP] UDP服务端 UDP客户端 UDP指令版服务端 UDP指令版客户端 3 [HTTP] HTTP服务端 ...

  10. 给WEB初学者一些有效率的建议

    因为IT互联网发展的非常迅速,而web前端这块很火,目前工资水平给的很高,在市场上也是非常的稀缺人才,现在各个行业转行做web前端的很多,今天给大家一些建议,希望新手少走点弯路吧! 建议一:有一个比较 ...