SQLite数据访问类(.NETCF)

using System;
using System.Data;
using System.Data.SQLite;

namespace Util
{
    /// <summary>
    /// SQLiteHelper SQLite数据库辅助类
    /// </summary>
    public class SQLiteHelper : IDisposable
    {
        #region 字段
        private string connectionString;
        private SQLiteConnection databaseConnection;
        #endregion

        #region 属性
        /// <summary>
        /// Gets the connection string for this instance.
        /// </summary>
        public string ConnectionString
        {
            get { return connectionString; }
        }
        #endregion

        #region 构造函数
        public SQLiteHelper(){}

        public SQLiteHelper(string connectionString)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            this.connectionString = connectionString;
            CreateConnection();
        }
        #endregion

        #region 方法
        /// <summary>
        /// Closes the current connection. You should call this method when you are completely
        /// done using this database instance. Methods will fail after you've disposed of this
        /// instance.
        /// </summary>
        public void Dispose()
        {
            if (databaseConnection != null)
            {
                databaseConnection.Close();
                databaseConnection = null;
            }
        }

        /// <summary>
        /// Creates a new, unopened connection instance for this database.
        /// </summary>
        /// <returns>
        /// An unopened <see cref="SQLiteConnection"/> for this database.
        /// </returns>
        /// <seealso cref="SQLiteConnection"/>       
        private void CreateConnection()
        {
            if (databaseConnection == null)
            {
                databaseConnection = new SQLiteConnection();
                databaseConnection.ConnectionString = ConnectionString;
            }
        }

        /// <summary>
        /// <para>Returns the shared connection, and opens it the first startTime.</para>
        /// </summary>
        /// <returns>The opened connection.</returns>
        public SQLiteConnection GetConnection()
        {
            if (databaseConnection.State != ConnectionState.Open)
            {
                databaseConnection.Open();
            }

            return databaseConnection;
        }

        /// <summary>
        /// Closes the shared connection.
        /// </summary>
        public void CloseConnection()
        {
            if (databaseConnection.State != ConnectionState.Closed)
            {
                databaseConnection.Close();
            }
        }

        /// <summary>
        /// Builds a value parameter name for the current database by ensuring there is an '@' at the
        /// start of the name.
        /// </summary>
        /// <param name="name">The name of the parameter.</param>
        /// <returns>A correctly formated parameter name, which starts with an '@'.</returns>
        public string BuildParameterName(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (name.Trim().Length == 0)
            {
                throw new ArgumentException("The string cannot be empty.", "name");
            }

            if (name[0] != '@')
            {
                return "@" + name;
            }
            else
            {
                return name;
            }
        }

        /// <summary>
        /// Creates a new parameter and sets the name of the parameter.
        /// </summary>
        /// <param name="name">The name of the parameter.</param>
        /// <returns>
        ///  A new <see cref="SQLiteParameter"/> instance of the correct type for this database.</returns>
        /// <remarks>
        /// The database will automatically add the correct prefix, like "@" for SQLite, to the
        /// parameter name. In other words, you can just supply the name without a prefix.
        /// </remarks>
        public SQLiteParameter CreateParameter(string name)
        {
            SQLiteParameter parameter = new SQLiteParameter();
            parameter.ParameterName = BuildParameterName(name);

            return parameter;
        }

        /// <summary>
        /// Creates a new parameter and sets the name of the parameter.
        /// </summary>
        /// <param name="name">The name of the parameter.</param>
        /// <param name="value">
        /// The value you want assigned to thsi parameter. A null value will be converted to
        /// a <see cref="DBNull"/> value in the parameter.
        /// </param>
        /// <returns>
        /// A new <see cref="SQLiteParameter"/> instance of the correct type for this database.</returns>
        /// <remarks>
        /// The database will automatically add the correct prefix, like "@" for SQLite, to the
        /// parameter name. In other words, you can just supply the name without a prefix.
        /// </remarks>
        public SQLiteParameter CreateParameter(string name, object value)
        {
            SQLiteParameter param = CreateParameter(name);
            param.Value = (value == null) ? DBNull.Value : value;

            return param;
        }

        /// <summary>
        /// Creates a new parameter and sets the name of the parameter.
        /// </summary>
        /// <param name="name">The name of the parameter.</param>
        /// <param name="type">The type of the parameter.</param>
        /// <param name="size">The size of this parameter.</param>
        /// <param name="value">
        /// The value you want assigned to this parameter. A null value will be converted to
        /// a <see cref="DBNull"/> value in the parameter.
        /// </param>
        /// <returns>
        /// A new <see cref="SQLiteParameter"/> instance of the correct type for this database.</returns>
        /// <remarks>
        /// The database will automatically add the correct prefix, like "@" for SQLite, to the
        /// parameter name. In other words, you can just supply the name without a prefix.
        /// </remarks>
        public SQLiteParameter CreateParameter(string name, DbType type, int size, object value)
        {
            SQLiteParameter param = CreateParameter(name);
            param.DbType = type;
            param.Size = size;
            param.Value = (value == null) ? DBNull.Value : value;

            return param;
        }

        /// <summary>
        /// Executes an SQL query with an optional set of parameters.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>The number of rows affected.</returns>
        public int ExecuteNonQuery(SQLiteCommand command, params SQLiteParameter[] parameters)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            int result;
            SQLiteConnection connection = GetConnection();
            PrepareCommand(command, connection, parameters);
            result = command.ExecuteNonQuery();

            return result;
        }

        /// <summary>
        /// Executes an SQL query with an optional set of parameters.
        /// </summary>
        /// <param name="strSql">The SQL statement to execute.</param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>The number of rows affected.</returns>
        public int ExecuteNonQuery(string strSql, params SQLiteParameter[] parameters)
        {
            if (strSql == null)
            {
                throw new ArgumentNullException("strSql");
            }

            using (SQLiteCommand command = new SQLiteCommand())
            {
                command.CommandText = strSql;
                return ExecuteNonQuery(command, parameters);
            }
        }

        /// <summary>
        /// Execute a command and return a <see cref="SQLiteDataReader"/> that contains the rows
        /// returned.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>A <see cref="SQLiteDataReader"/> that contains the rows returned by the query.</returns>
        public SQLiteDataReader ExecuteReader(SQLiteCommand command, params SQLiteParameter[] parameters)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            SQLiteDataReader result;
            SQLiteConnection connection = GetConnection();
            PrepareCommand(command, connection, parameters);
            result = command.ExecuteReader();

            return result;
        }

        /// <summary>
        /// Execute a command and return a <see cref="SQLiteDataReader"/> that contains the rows
        /// returned.
        /// </summary>
        /// <param name="strSql">The SQL query to execute.</param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>A <see cref="SQLiteDataReader"/> that contains the rows returned by the query.</returns>
        public SQLiteDataReader ExecuteReader(string strSql, params SQLiteParameter[] parameters)
        {
            if (strSql == null)
            {
                throw new ArgumentNullException("strSql");
            }

            if (strSql.Trim().Length == 0)
            {
                throw new ArgumentException("The string cannot be empty.", "strSql");
            }

            using (SQLiteCommand command = new SQLiteCommand())
            {
                command.CommandText = strSql;
                return ExecuteReader(command, parameters);
            }
        }

        /// <summary>
        /// <para>
        /// Executes the <paramref name="command"/> and returns the first column of the first
        /// row in the result set returned by the query. Extra columns or rows are ignored.
        /// </para>
        /// </summary>
        /// <param name="command">
        /// <para>
        /// The command that contains the query to execute.
        /// </para>
        /// </param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>
        /// <para>
        /// The first column of the first row in the result set.
        /// </para>
        /// </returns>
        /// <seealso cref="ISQLiteCommand.ExecuteScalar"/>
        public object ExecuteScalar(SQLiteCommand command, params SQLiteParameter[] parameters)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            object result;
            SQLiteConnection connection = GetConnection();
            PrepareCommand(command, connection, parameters);
            result = command.ExecuteScalar();

            return result;
        }

        /// <summary>
        /// Executes the <paramref name="command"/> and returns the first column of the first
        /// row in the result set returned by the query. Extra columns or rows are ignored.
        /// </summary>
        /// <param name="strSql">The SQL statement to execute.</param>
        /// <param name="parameters">Zero or more parameters for the query.</param>
        /// <returns>
        /// <para>
        /// The first column of the first row in the result set.
        /// </para>
        /// </returns>
        /// <seealso cref="ISQLiteCommand.ExecuteScalar"/>
        public object ExecuteScalar(string strSql, params SQLiteParameter[] parameters)
        {
            if (strSql == null)
            {
                throw new ArgumentNullException("strSql");
            }

            if (strSql.Trim().Length == 0)
            {
                throw new ArgumentException("The string cannot be empty.", "strSql");
            }

            using (SQLiteCommand command = new SQLiteCommand())
            {
                command.CommandText = strSql;
                return ExecuteScalar(command, parameters);
            }
        }

        /// <summary>
        /// <para>
        /// Assigns a <paramref name="connection"/> to the <paramref name="command"/> and
        /// discovers parameters if needed.
        /// </para>
        /// </summary>
        /// <param name="command">The command that contains the query to prepare.</param>
        /// <param name="connection">The connection to assign to the command.</param>
        private static void PrepareCommand(SQLiteCommand command, SQLiteConnection connection)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            command.Connection = connection;
        }

        /// <summary>
        /// Prepares a <see cref="SQLiteCommand"/> object for use. This involves setting the connection
        /// and adding any parameters to the command.
        /// </summary>
        /// <param name="command">The command object you want prepared.</param>
        /// <param name="connection">The connection to use with the command.</param>
        /// <param name="parameters">Zero or more parameters to add to the command.</param>
        private void PrepareCommand(SQLiteCommand command, SQLiteConnection connection, params SQLiteParameter[] parameters)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            command.Connection = connection;
            if (parameters != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    command.Parameters.Add(parameters[i]);
                }
            }
        }

        /// <summary>
        /// Checks to see if a table exists in the open database.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        /// <returns>true if the table exists, otherwise false.</returns>
        public bool TableExists(string tableName)
        {
            if (tableName == null)
            {
                throw new ArgumentNullException("tableName");
            }
            if (tableName.Trim().Length == 0)
            {
                throw new ArgumentException("The string cannot be empty.", "tableName");
            }

            string strSql = "SELECT name FROM sqlite_master WHERE name=@TableName";

            SQLiteParameter param = CreateParameter("@TableName", DbType.String, 512, tableName);
            SQLiteDataReader rdr = ExecuteReader(strSql, param);

            return rdr.HasRows;
        }

        /// <summary>
        /// This is a simple helper method that will convert a DBNull value into
        /// a null value.
        /// </summary>
        /// <param name="value">The value you want to check for DBNull</param>
        /// <returns>Null if <paramref name="value"/> is DBNull.Value, or <paramref name="value"/>.</returns>
        public static object GetNullable(object value)
        {
            return (value is DBNull) ? null : value;
        }

        #endregion
    }
}

转自:http://www.cnblogs.com/bobli/archive/2011/01/04/1925893.html
posted @ 2011-05-16 14:57  chlyzone  阅读(365)  评论(0编辑  收藏  举报