C# SqlHelper
singSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceCarHailing.Base{///<summary>///数据库帮助类///</summary>publicclassSqlHelp{///<summary>///创建一个已打开的连接///</summary>///<returns></returns>privatestaticSqlConnectionCreateConn(){SqlConnectionconn=newSqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);conn.Open();returnconn;}///<summary>///执行sql语句,返回受影响的行数///</summary>///<paramname="sql"></param>///<returns></returns>publicstaticintExecuteNonQuery(stringsql){returnExecuteNonQuery(sql,null);}///<summary>///执行sql语句,返回受影响的行数///</summary>///<paramname="sql"></param>///<returns></returns>publicstaticintExecuteNonQuery(stringsql,SqlParameter[]ps){SqlConnectionconn=CreateConn();SqlCommandcmd=newSqlCommand(sql,conn);try{if(ps!=null){cmd.Parameters.AddRange(ps);}returncmd.ExecuteNonQuery();}catch(Exceptionex){return0;}finally{conn.Close();}}///<summary>///执行sql语句,返回一个结果表///</summary>///<paramname="sql"></param>///<returns></returns>publicstaticDataTableExecuteSelectDataTable(stringsql){returnExecuteSelectDataTable(sql,null);}///<summary>///执行sql语句,返回一个结果表///</summary>///<paramname="sql"></param>///<paramname="ps"></param>///<returns></returns>publicstaticDataTableExecuteSelectDataTable(stringsql,SqlParameter[]ps=null){SqlConnectionconn=CreateConn();SqlCommandcmd=newSqlCommand(sql,conn);try{if(ps!=null){cmd.Parameters.AddRange(ps);}//SqlDataAdaptersda=newSqlDataAdapter(cmd);SqlDataReaderread=cmd.ExecuteReader();DataTabletable=newDataTable();table.Load(read);//DataSetds=newDataSet();//sda.Fill(ds);returntable;}finally{conn.Close();}}///<summary>//////</summary>///<paramname="sql"></param>///<returns></returns>decimalpublicstaticDataTableExecuteSelectPageDataTable(stringsql,refSqlParameter[]ps){SqlConnectionconn=CreateConn();SqlCommandcmd=newSqlCommand(sql,conn);cmd.CommandType=CommandType.StoredProcedure;try{cmd.Parameters.AddRange(ps);SqlDataAdaptersda=newSqlDataAdapter(cmd);DataSetds=newDataSet();sda.Fill(ds);returnds.Tables[0];}catch(SqlExceptionex){throwex;}finally{conn.Close();}}//publicstaticSqlDataReaderExecuteReader(stringcmdText,CommandTypecmdType,paramsSqlParameter[]cmdParms)//{//SqlCommandcmd=newSqlCommand();//SqlConnectionconn=CreateConn();//try//{//ProCommand(cmd,conn,cmdText,cmdType,cmdParms);//SqlDataReaderrdr=cmd.ExecuteReader(CommandBehavior.CloseConnection);////cmd.Parameters.Clear();//放到这里,返回参数会被清空。//returnrdr;//}//catch//{//conn.Close();//throw;//}//}///<summary>///分页读取数据///</summary>///<paramname="query">select查询语句</param>///<paramname="pageSize">每页显示数据数</param>///<paramname="PageIndex">当前页码</param>///<paramname="dt">存储数据的DataTable实例</param>publicstaticvoidPageDataTable(stringquery,intpageSize,intPageIndex,DataTabledt){//读取数据的开始索引longstartIndex=(PageIndex-1)*pageSize;//读取数据的结束索引longendIndex=PageIndex*pageSize-1;//DataReader读取的当前数据行的索引longreadToIndex=-1;using(SqlConnectionconn=CreateConn()){SqlCommandcmd=newSqlCommand(query,conn);//conn.Open();SqlDataReaderdr=cmd.ExecuteReader();//数据源中的列数intcols=dr.VisibleFieldCount;//构造DataTable结构for(inti=0;i<cols;i++){dt.Columns.Add(newDataColumn(dr.GetName(i),dr.GetFieldType(i)));}//读取数据,将数据一行一行添加到DataTablewhile(dr.Read()){readToIndex++;//当DataReader指针在开始索引和结束索引闭区间时才读取数据构造DataRow//并添加到DataTableif(readToIndex>=startIndex&&readToIndex<=endIndex){DataRowrow=dt.NewRow();for(inti=0;i<cols;i++){row[i]=dr[i];}dt.Rows.Add(row);}}dr.Close();}}}}
//using MySql.Data.MySqlClient; #region 执行简单SQL语句,使用MySQL查询 static string strConn = "server=.;database=Data20180608;uid=sa;pwd=123456;integrated Security=SSPI;persist Security info=false;"; /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int MyExecuteSql(string SQLString) { using (MySqlConnection connection = new MySqlConnection(strConn)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataTable MyQuery(string SQLString) { using (MySqlConnection connection = new MySqlConnection(strConn)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } #endregion Mysql
#region 执行简单SQL语句,使用SQL SERVER查询 static string strConn = "Data Source=.;database=Data20180608;User id=root;Password=123456;pooling=false;CharSet=utf8;port=3306;"; /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(strConn)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataTable Query(string SQLString) { using (SqlConnection connection = new SqlConnection(strConn)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } #endregion Sql server
//using System.Data.OleDb; public static string OtherPAth = ""; public static string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="; public static string Sql = String.Empty; #region 执行简单SQL语句,使用OleDb查询 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth )) { using (OleDbCommand cmd = new OleDbCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataTable Query(string SQLString) { using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth)) { DataSet ds = new DataSet(); try { connection.Open(); OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return ds.Tables[0]; } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataTable QueryDataName() { using (OleDbConnection connection = new OleDbConnection(strConn + OtherPAth)) { DataTable ds = new DataTable(); try { connection.Open(); ds = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return ds; } } #endregion Access
public static string strConn = @"Data Source=" + @"F:\资料文档\20190227\CAD\0625AnPin\CadDLLcl\Data\Cad_try0626.db"; public static string Sql = String.Empty; /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(strConn)) { //事务 using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); cmd.Transaction = singleTrans; int rows = cmd.ExecuteNonQuery(); singleTrans.Commit(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); singleTrans.Rollback(); throw e; } } } } } /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name = "SQLString" > 查询语句 </ param > /// < returns > DataSet </ returns > public static DataTable Query(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(strConn)) { DataSet ds = new DataSet(); try { connection.Open(); SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); command.Fill(ds, "ds"); return ds.Tables[0]; } catch (Exception ex) { connection.Close(); throw ex; } } } /// <summary> /// 执行存储过程,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteProc(string procName, SQLiteParameter[] coll) { using (SQLiteConnection connection = new SQLiteConnection(strConn)) { //事务 using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { using (SQLiteCommand cmd = new SQLiteCommand(connection)) { try { connection.Open(); for (int i = 0; i < coll.Length; i++) { cmd.Parameters.Add(coll[i]); } cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = procName; cmd.Transaction = singleTrans; int rows = cmd.ExecuteNonQuery(); singleTrans.Commit(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); singleTrans.Rollback(); throw e; } } } } } /// <summary> /// 执行带参数的SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlPar(string sqlPar, SQLiteParameter[] coll) { using (SQLiteConnection connection = new SQLiteConnection(strConn)) { //事务 using (SQLiteTransaction singleTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { using (SQLiteCommand cmd = new SQLiteCommand(connection)) { try { connection.Open(); for (int i = 0; i < coll.Length; i++) { cmd.Parameters.Add(coll[i]); } cmd.CommandType = CommandType.Text; cmd.CommandText = sqlPar; cmd.Transaction = singleTrans; int rows = cmd.ExecuteNonQuery(); singleTrans.Commit(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); singleTrans.Rollback(); throw e; } } } } } Sqlite