C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法

本文实例讲述了C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法。分享给大家供大家参考。具体如下:

这个类不是我实现的,英文原文地址为http://www.eggheadcafe.com/articles/20050315.asp,这里修改了原文中分析sql语句参数的方法,将方法名修改为AttachParameters,将其修饰符修改为private,并直接传递command到这个方法,直接绑定参数到comand。修改后的代码如下

using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.Collections;
using System.Data.SQLite;
namespace DBUtility.SQLite
{
 /// <summary>
 /// SQLiteHelper is a utility class similar to "SQLHelper" in MS
 /// Data Access Application Block and follows similar pattern.
 /// </summary>
 public class SQLiteHelper
 {
  /// <summary>
  /// Creates a new <see cref="SQLiteHelper"/> instance. The ctor is marked private since all members are static.
  /// </summary>
  private SQLiteHelper()
  {
  }
  /// <summary>
  /// Creates the command.
  /// </summary>
  /// <param name="connection">Connection.</param>
  /// <param name="commandText">Command text.</param>
  /// <param name="commandParameters">Command parameters.</param>
  /// <returns>SQLite Command</returns>
  public static SQLiteCommand CreateCommand(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
  {
   SQLiteCommand cmd = new SQLiteCommand(commandText, connection);
   if (commandParameters.Length > 0)
   {
    foreach (SQLiteParameter parm in commandParameters)
     cmd.Parameters.Add(parm);
   }
   return cmd;
  }
  /// <summary>
  /// Creates the command.
  /// </summary>
  /// <param name="connectionString">Connection string.</param>
  /// <param name="commandText">Command text.</param>
  /// <param name="commandParameters">Command parameters.</param>
  /// <returns>SQLite Command</returns>
  public static SQLiteCommand CreateCommand(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
  {
   SQLiteConnection cn = new SQLiteConnection(connectionString);
   SQLiteCommand cmd = new SQLiteCommand(commandText, cn);
   if (commandParameters.Length > 0)
   {
    foreach (SQLiteParameter parm in commandParameters)
     cmd.Parameters.Add(parm);
   }
   return cmd;
  }
  /// <summary>
  /// Creates the parameter.
  /// </summary>
  /// <param name="parameterName">Name of the parameter.</param>
  /// <param name="parameterType">Parameter type.</param>
  /// <param name="parameterValue">Parameter value.</param>
  /// <returns>SQLiteParameter</returns>
  public static SQLiteParameter CreateParameter(string parameterName, System.Data.DbType parameterType, object parameterValue)
  {
   SQLiteParameter parameter = new SQLiteParameter();
   parameter.DbType = parameterType;
   parameter.ParameterName = parameterName;
   parameter.Value = parameterValue;
   return parameter;
  }
  /// <summary>
  /// Shortcut method to execute dataset from SQL Statement and object[] arrray of parameter values
  /// </summary>
  /// <param name="connectionString">SQLite Connection string</param>
  /// <param name="commandText">SQL Statement with embedded "@param" style parameter names</param>
  /// <param name="paramList">object[] array of parameter values</param>
  /// <returns></returns>
  public static DataSet ExecuteDataSet(string connectionString, string commandText, object[] paramList)
  {
   SQLiteConnection cn = new SQLiteConnection(connectionString);
   SQLiteCommand cmd = cn.CreateCommand();

   cmd.CommandText = commandText;
   if (paramList != null)
   {
    AttachParameters(cmd,commandText, paramList);
   }
   DataSet ds = new DataSet();
   if (cn.State == ConnectionState.Closed)
    cn.Open();
   SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
   da.Fill(ds);
   da.Dispose();
   cmd.Dispose();
   cn.Close();
   return ds;
  }
  /// <summary>
  /// Shortcut method to execute dataset from SQL Statement and object[] arrray of parameter values
  /// </summary>
  /// <param name="cn">Connection.</param>
  /// <param name="commandText">Command text.</param>
  /// <param name="paramList">Param list.</param>
  /// <returns></returns>
  public static DataSet ExecuteDataSet(SQLiteConnection cn, string commandText, object[] paramList)
  {
   SQLiteCommand cmd = cn.CreateCommand();

   cmd.CommandText = commandText;
   if (paramList != null)
   {
    AttachParameters(cmd,commandText, paramList);
   }
   DataSet ds = new DataSet();
   if (cn.State == ConnectionState.Closed)
    cn.Open();
   SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
   da.Fill(ds);
   da.Dispose();
   cmd.Dispose();
   cn.Close();
   return ds;
  }
  /// <summary>
  /// Executes the dataset from a populated Command object.
  /// </summary>
  /// <param name="cmd">Fully populated SQLiteCommand</param>
  /// <returns>DataSet</returns>
  public static DataSet ExecuteDataset(SQLiteCommand cmd)
  {
   if (cmd.Connection.State == ConnectionState.Closed)
    cmd.Connection.Open();
   DataSet ds = new DataSet();
   SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
   da.Fill(ds);
   da.Dispose();
   cmd.Connection.Close();
   cmd.Dispose();
   return ds;
  }
  /// <summary>
  /// Executes the dataset in a SQLite Transaction
  /// </summary>
  /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call. </param>
  /// <param name="commandText">Command text.</param>
  /// <param name="commandParameters">Sqlite Command parameters.</param>
  /// <returns>DataSet</returns>
  /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
  public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
  {
   if (transaction == null) throw new ArgumentNullException("transaction");
   if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
   IDbCommand cmd = transaction.Connection.CreateCommand();
   cmd.CommandText = commandText;
   foreach (SQLiteParameter parm in commandParameters)
   {
    cmd.Parameters.Add(parm);
   }
   if (transaction.Connection.State == ConnectionState.Closed)
    transaction.Connection.Open();
   DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
   return ds;
  }
  /// <summary>
  /// Executes the dataset with Transaction and object array of parameter values.
  /// </summary>
  /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call. </param>
  /// <param name="commandText">Command text.</param>
  /// <param name="commandParameters">object[] array of parameter values.</param>
  /// <returns>DataSet</returns>
  /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
  public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, object[] commandParameters)
  {
   if (transaction == null) throw new ArgumentNullException("transaction");
   if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,               please provide an open transaction.", "transaction");
   IDbCommand cmd = transaction.Connection.CreateCommand();
   cmd.CommandText = commandText;
   AttachParameters((SQLiteCommand)cmd,cmd.CommandText, commandParameters);
   if (transaction.Connection.State == ConnectionState.Closed)
    transaction.Connection.Open();
   DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
   return ds;
  }
  #region UpdateDataset
  /// <summary>
  /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
  /// </summary>
  /// <remarks>
  /// e.g.:
  /// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
  /// </remarks>
  /// <param name="insertCommand">A valid SQL statement to insert new records into the data source</param>
  /// <param name="deleteCommand">A valid SQL statement to delete records from the data source</param>
  /// <param name="updateCommand">A valid SQL statement used to update records in the data source</param>
  /// <param name="dataSet">The DataSet used to update the data source</param>
  /// <param name="tableName">The DataTable used to update the data source.</param>
  public static void UpdateDataset(SQLiteCommand insertCommand, SQLiteCommand deleteCommand, SQLiteCommand updateCommand, DataSet dataSet, string tableName)
  {
   if (insertCommand == null) throw new ArgumentNullException("insertCommand");
   if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
   if (updateCommand == null) throw new ArgumentNullException("updateCommand");
   if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("tableName");
   // Create a SQLiteDataAdapter, and dispose of it after we are done
   using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter())
   {
    // Set the data adapter commands
    dataAdapter.UpdateCommand = updateCommand;
    dataAdapter.InsertCommand = insertCommand;
    dataAdapter.DeleteCommand = deleteCommand;
    // Update the dataset changes in the data source
    dataAdapter.Update(dataSet, tableName);
    // Commit all the changes made to the DataSet
    dataSet.AcceptChanges();
   }
  }
  #endregion

  /// <summary>
  /// ShortCut method to return IDataReader
  /// NOTE: You should explicitly close the Command.connection you passed in as
  /// well as call Dispose on the Command after reader is closed.
  /// We do this because IDataReader has no underlying Connection Property.
  /// </summary>
  /// <param name="cmd">SQLiteCommand Object</param>
  /// <param name="commandText">SQL Statement with optional embedded "@param" style parameters</param>
  /// <param name="paramList">object[] array of parameter values</param>
  /// <returns>IDataReader</returns>
  public static IDataReader ExecuteReader(SQLiteCommand cmd, string commandText, object[] paramList)
  {
   if (cmd.Connection == null)
    throw new ArgumentException("Command must have live connection attached.", "cmd");
   cmd.CommandText = commandText;
   AttachParameters(cmd,commandText, paramList);
   if (cmd.Connection.State == ConnectionState.Closed)
    cmd.Connection.Open();
   IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
   return rdr;
  }
  /// <summary>
  /// Shortcut to ExecuteNonQuery with SqlStatement and object[] param values
  /// </summary>
  /// <param name="connectionString">SQLite Connection String</param>
  /// <param name="commandText">Sql Statement with embedded "@param" style parameters</param>
  /// <param name="paramList">object[] array of parameter values</param>
  /// <returns></returns>
  public static int ExecuteNonQuery(string connectionString, string commandText, params object[] paramList)
  {
   SQLiteConnection cn = new SQLiteConnection(connectionString);
   SQLiteCommand cmd = cn.CreateCommand();
   cmd.CommandText = commandText;
   AttachParameters(cmd,commandText, paramList);
   if (cn.State == ConnectionState.Closed)
    cn.Open();
   int result = cmd.ExecuteNonQuery();
   cmd.Dispose();
   cn.Close();
   return result;
  }

  public static int ExecuteNonQuery(SQLiteConnection cn, string commandText, params object[] paramList)
  {
   SQLiteCommand cmd = cn.CreateCommand();
   cmd.CommandText = commandText;
   AttachParameters(cmd,commandText, paramList);
   if (cn.State == ConnectionState.Closed)
    cn.Open();
   int result = cmd.ExecuteNonQuery();
   cmd.Dispose();
   cn.Close();
   return result;
  }
  /// <summary>
  /// Executes non-query sql Statment with Transaction
  /// </summary>
  /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call. </param>
  /// <param name="commandText">Command text.</param>
  /// <param name="paramList">Param list.</param>
  /// <returns>Integer</returns>
  /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
  public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText, params object[] paramList)
  {
   if (transaction == null) throw new ArgumentNullException("transaction");
   if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,              please provide an open transaction.", "transaction");
   IDbCommand cmd = transaction.Connection.CreateCommand();
   cmd.CommandText = commandText;
   AttachParameters((SQLiteCommand)cmd,cmd.CommandText, paramList);
   if (transaction.Connection.State == ConnectionState.Closed)
    transaction.Connection.Open();
   int result = cmd.ExecuteNonQuery();
   cmd.Dispose();
   return result;
  }

  /// <summary>
  /// Executes the non query.
  /// </summary>
  /// <param name="cmd">CMD.</param>
  /// <returns></returns>
  public static int ExecuteNonQuery(IDbCommand cmd)
  {
   if (cmd.Connection.State == ConnectionState.Closed)
    cmd.Connection.Open();
   int result = cmd.ExecuteNonQuery();
   cmd.Connection.Close();
   cmd.Dispose();
   return result;
  }
  /// <summary>
  /// Shortcut to ExecuteScalar with Sql Statement embedded params and object[] param values
  /// </summary>
  /// <param name="connectionString">SQLite Connection String</param>
  /// <param name="commandText">SQL statment with embedded "@param" style parameters</param>
  /// <param name="paramList">object[] array of param values</param>
  /// <returns></returns>
  public static object ExecuteScalar(string connectionString, string commandText, params object[] paramList)
  {
   SQLiteConnection cn = new SQLiteConnection(connectionString);
   SQLiteCommand cmd = cn.CreateCommand();
   cmd.CommandText = commandText;
   AttachParameters(cmd,commandText, paramList);
   if (cn.State == ConnectionState.Closed)
    cn.Open();
   object result = cmd.ExecuteScalar();
   cmd.Dispose();
   cn.Close();
   return result;
  }
  /// <summary>
  /// Execute XmlReader with complete Command
  /// </summary>
  /// <param name="command">SQLite Command</param>
  /// <returns>XmlReader</returns>
  public static XmlReader ExecuteXmlReader(IDbCommand command)
  { // open the connection if necessary, but make sure we
   // know to close it when we�re done.
   if (command.Connection.State != ConnectionState.Open)
   {
    command.Connection.Open();
   }
   // get a data adapter
   SQLiteDataAdapter da = new SQLiteDataAdapter((SQLiteCommand)command);
   DataSet ds = new DataSet();
   // fill the data set, and return the schema information
   da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
   da.Fill(ds);
   // convert our dataset to XML
   StringReader stream = new StringReader(ds.GetXml());
   command.Connection.Close();
   // convert our stream of text to an XmlReader
   return new XmlTextReader(stream);
  }

  /// <summary>
  /// Parses parameter names from SQL Statement, assigns values from object array , /// and returns fully populated ParameterCollection.
  /// </summary>
  /// <param name="commandText">Sql Statement with "@param" style embedded parameters</param>
  /// <param name="paramList">object[] array of parameter values</param>
  /// <returns>SQLiteParameterCollection</returns>
  /// <remarks>Status experimental. Regex appears to be handling most issues. Note that parameter object array must be in same ///order as parameter names appear in SQL statement.</remarks>
  private static SQLiteParameterCollection AttachParameters(SQLiteCommand cmd, string commandText, params object[] paramList)
  {
   if (paramList == null || paramList.Length == 0) return null;
   SQLiteParameterCollection coll = cmd.Parameters;
   string parmString = commandText.Substring(commandText.IndexOf("@"));
   // pre-process the string so always at least 1 space after a comma.
   parmString = parmString.Replace(",", " ,");
   // get the named parameters into a match collection
   string pattern = @"(@)\S*(.*?)\b";
   Regex ex = new Regex(pattern, RegexOptions.IgnoreCase);
   MatchCollection mc = ex.Matches(parmString);
   string[] paramNames = new string[mc.Count];
   int i = 0;
   foreach (Match m in mc)
   {
    paramNames[i] = m.Value;
    i++;
   }
   // now let's type the parameters
   int j = 0;
   Type t = null;
   foreach (object o in paramList)
   {
    t = o.GetType();
    SQLiteParameter parm = new SQLiteParameter();
    switch (t.ToString())
    {
     case ("DBNull"):
     case ("Char"):
     case ("SByte"):
     case ("UInt16"):
     case ("UInt32"):
     case ("UInt64"):
      throw new SystemException("Invalid data type");

     case ("System.String"):
      parm.DbType = DbType.String;
      parm.ParameterName = paramNames[j];
      parm.Value = (string)paramList[j];
      coll.Add(parm);
      break;
     case ("System.Byte[]"):
      parm.DbType = DbType.Binary;
      parm.ParameterName = paramNames[j];
      parm.Value = (byte[])paramList[j];
      coll.Add(parm);
      break;
     case ("System.Int32"):
      parm.DbType = DbType.Int32;
      parm.ParameterName = paramNames[j];
      parm.Value = (int)paramList[j];
      coll.Add(parm);
      break;
     case ("System.Boolean"):
      parm.DbType = DbType.Boolean;
      parm.ParameterName = paramNames[j];
      parm.Value = (bool)paramList[j];
      coll.Add(parm);
      break;
     case ("System.DateTime"):
      parm.DbType = DbType.DateTime;
      parm.ParameterName = paramNames[j];
      parm.Value = Convert.ToDateTime(paramList[j]);
      coll.Add(parm);
      break;
     case ("System.Double"):
      parm.DbType = DbType.Double;
      parm.ParameterName = paramNames[j];
      parm.Value = Convert.ToDouble(paramList[j]);
      coll.Add(parm);
      break;
     case ("System.Decimal"):
      parm.DbType = DbType.Decimal;
      parm.ParameterName = paramNames[j];
      parm.Value = Convert.ToDecimal(paramList[j]);
      break;
     case ("System.Guid"):
      parm.DbType = DbType.Guid;
      parm.ParameterName = paramNames[j];
      parm.Value = (System.Guid)(paramList[j]);
      break;
     case ("System.Object"):
      parm.DbType = DbType.Object;
      parm.ParameterName = paramNames[j];
      parm.Value = paramList[j];
      coll.Add(parm);
      break;
     default:
      throw new SystemException("Value is of unknown data type");
    } // end switch
    j++;
   }
   return coll;
  }
  /// <summary>
  /// Executes non query typed params from a DataRow
  /// </summary>
  /// <param name="command">Command.</param>
  /// <param name="dataRow">Data row.</param>
  /// <returns>Integer result code</returns>
  public static int ExecuteNonQueryTypedParams(IDbCommand command, DataRow dataRow)
  {
   int retVal = 0;
   // If the row has values, the store procedure parameters must be initialized
   if (dataRow != null && dataRow.ItemArray.Length > 0)
   {
    // Set the parameters values
    AssignParameterValues(command.Parameters, dataRow);
    retVal = ExecuteNonQuery(command);
   }
   else
   {
    retVal = ExecuteNonQuery(command);
   }
   return retVal;
  }
  /// <summary>
  /// This method assigns dataRow column values to an IDataParameterCollection
  /// </summary>
  /// <param name="commandParameters">The IDataParameterCollection to be assigned values</param>
  /// <param name="dataRow">The dataRow used to hold the command's parameter values</param>
  /// <exception cref="System.InvalidOperationException">Thrown if any of the parameter names are invalid.</exception>
  protected internal static void AssignParameterValues(IDataParameterCollection commandParameters, DataRow dataRow)
  {
   if (commandParameters == null || dataRow == null)
   {
    // Do nothing if we get no data
    return;
   }
   DataColumnCollection columns = dataRow.Table.Columns;
   int i = 0;
   // Set the parameters values
   foreach (IDataParameter commandParameter in commandParameters)
   {
    // Check the parameter name
    if (commandParameter.ParameterName == null ||
     commandParameter.ParameterName.Length <= 1)
     throw new InvalidOperationException(string.Format(
       "Please provide a valid parameter name on the parameter #{0},       the ParameterName property has the following value: '{1}'.",
      i, commandParameter.ParameterName));
    if (columns.Contains(commandParameter.ParameterName))
     commandParameter.Value = dataRow[commandParameter.ParameterName];
    else if (columns.Contains(commandParameter.ParameterName.Substring(1)))
     commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
    i++;
   }
  }
  /// <summary>
  /// This method assigns dataRow column values to an array of IDataParameters
  /// </summary>
  /// <param name="commandParameters">Array of IDataParameters to be assigned values</param>
  /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
  /// <exception cref="System.InvalidOperationException">Thrown if any of the parameter names are invalid.</exception>
  protected void AssignParameterValues(IDataParameter[] commandParameters, DataRow dataRow)
  {
   if ((commandParameters == null) || (dataRow == null))
   {
    // Do nothing if we get no data
    return;
   }
   DataColumnCollection columns = dataRow.Table.Columns;
   int i = 0;
   // Set the parameters values
   foreach (IDataParameter commandParameter in commandParameters)
   {
    // Check the parameter name
    if (commandParameter.ParameterName == null ||
     commandParameter.ParameterName.Length <= 1)
     throw new InvalidOperationException(string.Format(
      "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
      i, commandParameter.ParameterName));
    if (columns.Contains(commandParameter.ParameterName))
     commandParameter.Value = dataRow[commandParameter.ParameterName];
    else if (columns.Contains(commandParameter.ParameterName.Substring(1)))
     commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
    i++;
   }
  }
  /// <summary>
  /// This method assigns an array of values to an array of IDataParameters
  /// </summary>
  /// <param name="commandParameters">Array of IDataParameters to be assigned values</param>
  /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  /// <exception cref="System.ArgumentException">Thrown if an incorrect number of parameters are passed.</exception>
  protected void AssignParameterValues(IDataParameter[] commandParameters, params object[] parameterValues)
  {
   if ((commandParameters == null) || (parameterValues == null))
   {
    // Do nothing if we get no data
    return;
   }
   // We must have the same number of values as we pave parameters to put them in
   if (commandParameters.Length != parameterValues.Length)
   {
    throw new ArgumentException("Parameter count does not match Parameter Value count.");
   }
   // Iterate through the IDataParameters, assigning the values from the corresponding position in the
   // value array
   for (int i = 0, j = commandParameters.Length, k = 0; i < j; i++)
   {
    if (commandParameters[i].Direction != ParameterDirection.ReturnValue)
    {
     // If the current array value derives from IDataParameter, then assign its Value property
     if (parameterValues[k] is IDataParameter)
     {
      IDataParameter paramInstance;
      paramInstance = (IDataParameter)parameterValues[k];
      if (paramInstance.Direction == ParameterDirection.ReturnValue)
      {
       paramInstance = (IDataParameter)parameterValues[++k];
      }
      if (paramInstance.Value == null)
      {
       commandParameters[i].Value = DBNull.Value;
      }
      else
      {
       commandParameters[i].Value = paramInstance.Value;
      }
     }
     else if (parameterValues[k] == null)
     {
      commandParameters[i].Value = DBNull.Value;
     }
     else
     {
      commandParameters[i].Value = parameterValues[k];
     }
     k++;
    }
   }
  }
 }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • c#中SqlHelper封装SqlDataReader的方法

    本文实例讲述了c#中SqlHelper封装SqlDataReader的方法.分享给大家供大家参考.具体如下: /// <summary> /// 执行sql语句返回一个DataReader /// 当返回DataReader的时候,注意: /// 1.Connection不能关闭 /// 2.DataReader不能关闭 /// 3.command对象执行ExecuteReader()的时候需要传递一个参数CommandBehavior.CloseConnection /// </sum

  • c# SQLHelper(for winForm)实现代码

    SQLHelper.cs 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace HelloWinForm.DBUtility { class SQLHelper { #reg

  • C#实现较为实用的SQLhelper

    第一次写博客,想不到写什么好b( ̄▽ ̄)d ,考虑的半天决定从sqlhelper开始,sqlhelper对程序员来说就像helloworld一样,很简单却又很重要,helloworld代表着程序员萌新第一次写代码,而sqlhelper则是初次接触数据库(不知道这种说法对不对). 好了不废话了,下面直接上代码(无话可说了): public class SQLHelper { // 超时时间 private static int Timeout = 1000; // 数据库名称 public con

  • C#编写SqlHelper类

    无聊的周末,学习.编码无力.想找点事干但又不知道干点什么,猛然发现自己学过的SqlHelper快忘记了.于是乎虎躯一震心想怎能如此堕落下去,立马打开电脑,双手摸上键盘.写下此文作为学习过程中的复习,并分享出知识(顺便打发时间-^.^-). 下面开始正文 这里以控制台程序为案例.首先我们需要先配置一下连接字符串,我们需要在app.config文件中增加如下节点: <connectionStrings> <add name="Sql" connectionString=&

  • C#实现操作MySql数据层类MysqlHelper实例

    本文实例讲述了C#实现操作MySql数据层类MysqlHelper.分享给大家供大家参考.具体如下: using System; using System.Data; using System.Configuration; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using MySql.Data; using MySql.Data.MySqlCli

  • C# SqlHelper应用开发学习

    本文实例为大家分享了C# SqlHelper应用技巧,供大家参考,具体内容如下 使用App.config配置文件封装连接字符串,方便重复使用 --->添加App.conifg配置文件 --->Add : ConnectionString: --->添加引用 <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supported

  • C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法

    本文实例讲述了C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法.分享给大家供大家参考.具体如下: 这个类不是我实现的,英文原文地址为http://www.eggheadcafe.com/articles/20050315.asp,这里修改了原文中分析sql语句参数的方法,将方法名修改为AttachParameters,将其修饰符修改为private,并直接传递command到这个方法,直接绑定参数到comand.修改后的代码如下 using System;

  • 基于Java中Math类的常用函数总结

    Java中比较常用的几个数学公式的总结: //取整,返回小于目标函数的最大整数,如下将会返回-2 Math.floor(-1.8): //取整,返回发育目标数的最小整数 Math.ceil() //四舍五入取整 Math.round() //计算平方根 Math.sqrt() //计算立方根 Math.cbrt() //返回欧拉数e的n次幂 Math.exp(3); //计算乘方,下面是计算3的2次方 Math.pow(3,2); //计算自然对数 Math.log(); //计算绝对值 Mat

  • 基于vue的tab-list类目切换商品列表组件的示例代码

    在大多数电商场景中,页面都会有类目切换加上商品列表的部分,页面大概会长这样 每次写类似场景的时候,都需要去为类目商品列表写很多逻辑,为了提高开发效率我决定将这一部分抽离成组件. 实现 1.样式 所有tab栏的样式和商品列表的样式都提供插槽,供业务自己定制 2.变量 isTabFixed: false,//是否吸顶 tab: 1,//当前tab page: 1,//当前页数 listStatus: { finished: false,//是否已是最后一页 loading: false,//是否加载

  • java自定义Scanner类似功能类的实例讲解

    读取键盘输入 package com.zjx.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * 面试题 * 读取键盘各个数据类型 * */ public class TestFaceIo { public static void main(String[] args) { System.out.print("请输入姓名: "); S

  • 基于spring三方包类注入容器的四种方式小结

    如果引用第三方jar包,肯定是不能直接使用常用注解@Controller.@Service.@Repository.@Component将类的实例注入到spring容器中.以下四种方法可以向spring容器中导入三方包中类实例 . 1 xml配置 这种情况大家用的比较多,就是在spring的xml文件中配置需要导入的bean.在springweb项目工程web.xml中 ContextLoaderListener或者DispatcherServlet的初始参数contextConfigLocat

  • 基于java涉及父子类的异常详解

    java中的异常涉及到父子类的问题,可以归纳为一句话:子类的构造函数抛出的异常必须包含父类的异常,子类的方法可以选择抛出"范围小于等于"父类的异常或不抛出异常. 1. 为什么构造函数必须抛出包含父类的异常? 在<thingking in java>中有这么一段话: 异常限制:当覆盖方法时,只能抛出在基类方法的异常说明中列出的那些异常 异常限制对构造器不起作用,你会发现StormyInning的构造器可以抛出任何异常,而不必理会基类构造函数所抛出的异常.然而因为必须构造函数必

  • 微软官方SqlHelper类 数据库辅助操作类 原创

    数据库操作类真的没有必要自己去写,因为成熟的类库真的非常完善了,拿来直接用就好,省时省力. 本文就为大家介绍微软官方的程序PetShop4.0中的SqlHelper类,先来做一下简单的介绍,PetShop是一个范例,微软用它来展示.Net企业系统开发的能力. 那SqlHelper中封装了哪些方法呢? 里面的函数一堆,常用的就那几个,无非就是增删改查嘛,来看下几种常用的函数: 1.ExecuteNonQuery 执行增删改 2.ExecuteReader 执行查询 3.ExecuteScalar

  • JavaScript实现基于Cookie的存储类实例

    本文实例讲述了JavaScript实现基于Cookie的存储类.分享给大家供大家参考.具体分析如下: 通过这个JS类,你可以象使用session一样使用cookie,非常简单了! /* * CookieStorage.js * 本类实现像localStorage和sessionStorage一样的存储API * 不同的是,它是基于HTTP Cookies实现的. */ function CookieStorage(maxage, path) { // 两个参数分别代表储存有效期和作用域 // 获

  • PHP基于单例模式编写PDO类的方法

    一.单例模式简介 简单的说,一个对象(在学习设计模式之前,需要比较了解面向对象思想)只负责一个特定的任务: 二.为什么要使用PHP单例模式? 1.php的应用主要在于数据库应用, 所以一个应用中会存在大量的数据库操作, 使用单例模式, 则可以避免大量的new 操作消耗的资源. 2.如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现. 这个可以参看ZF的FrontController部分. 3.在一次页面请求中, 便于进行调试, 因为所有的代码(例如数据库操作类db)

随机推荐