熙熙-SQLCE类-熙熙

今天有位朋友leray提到想在wince上安装个嵌入式数据库,想问我一些更多的细节。

怎么说呢,其实就是按照熙熙在之前写的《WinCE平台搭建数据库(wince6.0+vs2008+sqlce)-熙熙》步骤一步一步来的,选的数据库型号很明显只能是SQLCE,这篇帖子里面已经说的很清楚了,要安装的文件在哪找、如何安装等等。用VS2005也是可以的。

另外,我再贴一段代码,用于wince数据库连接和执行SQL语句的。其实就是根据网上下载的代码改的,有的命名空间和类,加了个-ce的后缀,就完事了。其实我自己处理有点点麻烦的就是wince系统中的路径问题,因为在这段代码中,SQL连接字符串直接连接到数据库文件的,得用程序找到这个文件的路径才行,搞得自己一个头两个大,改天再说了,先上代码: 

小二~上代码!

好嘞,客官。

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlServerCe;
using System.Data;

namespace TabControl
{
    class sqlce_class
    {
        public static string Sql_conn_str = @"Data Source=db.sdf";

        #region 数据库链接方法       
        /// <summary>
        /// 取得一个连接对象
        /// </summary>
        /// <returns></returns>
        public static SqlCeConnection GetConnection()//取得数据库链接
        {
            return new SqlCeConnection(Sql_conn_str);
        }
       
        public static bool TestConnection()//测试连接
        {
            try
            {
                SqlCeConnection sqlconn = GetConnection();
                sqlconn.Open();
                sqlconn.Close();
                return true;
                //MessageBox.Show("数据库可以连接!", "提示:");
            }
            catch
            {
                return false;
                //MessageBox.Show("数据库连接发生错误!", "错误:");//异常提示
            }
        }

        ~sqlce_class()//析构
        {
        }
        #endregion

        #region 存在判断
        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool TabExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
            DataSet ds = sqlce_class.GetDataSetSQL(strsql);
            int cmdresult;
            cmdresult = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return cmdresult > 0;
        }
        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
            DataSet ds = sqlce_class.GetDataSetSQL(sql);
            int cmdresult;
            cmdresult = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return cmdresult > 0;
        }
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            DataSet ds = sqlce_class.GetDataSetSQL(strsql);
            int cmdresult;
            cmdresult = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return cmdresult;
        }
        public static bool Exists(string strSql)
        {
            DataSet ds = sqlce_class.GetDataSetSQL(strSql);
            int cmdresult;
            cmdresult = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return cmdresult > 0;
        }
        public static bool Exists(string strSql, IDataParameter[] parameters)
        {
            DataSet ds = sqlce_class.GetDataSetSQL(strSql, parameters);
            int cmdresult;
            cmdresult = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return cmdresult > 0;
        }
        #endregion
       
        #region 数据库操作方法  读取、执行sql语句、

        #region 读取
        /// <summary>
        /// 执行查询语句,返回OleDbDataReader ( 注意:调用该方法后,一定要对OleDbDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlCeDataReader</returns>
        public static SqlCeDataReader GetReaderSQL(string strSQL)
        {
            SqlCeConnection connection = GetConnection();
            SqlCeCommand cmd = new SqlCeCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlServerCe.SqlCeException e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 执行存储过程,返回OleDbDataReader ( 注意:调用该方法后,一定要对OleDbDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCeDataReader</returns>
        public static SqlCeDataReader GetReaderProc(string storedProcName, IDataParameter[] parameters)
        {
            SqlCeConnection connection = GetConnection();
            SqlCeDataReader returnReader;
            SqlCeCommand command = new SqlCeCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlCeParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            connection.Open();
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;
        }

        public static DataSet GetDataSetSQL(string SQLString)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                DataSet ds = new DataSet();
                SqlCeDataAdapter command = new SqlCeDataAdapter(SQLString, connection);
                try
                {
                    connection.Open();

                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlServerCe.SqlCeException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    command.Dispose();
                    connection.Close();
                }
                return ds;
            }
        }
        public static DataSet GetDataSetSQL(SqlCeCommand cmd)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                DataSet ds = new DataSet();
                cmd.Connection = connection;
                SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
                try
                {
                    connection.Open();
                    da.Fill(ds, "ds");
                }
                catch (System.Data.SqlServerCe.SqlCeException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    da.Dispose();
                    connection.Close();
                }
                return ds;
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSetSQL(string SQLString, params SqlCeParameter[] cmdParms)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                SqlCeCommand cmd = new SqlCeCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlCeDataAdapter da = new SqlCeDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlServerCe.SqlCeException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                    return ds;
                }
            }
        }
        public static DataSet GetDataSetSQL(string SQLString, params IDataParameter[] cmdParms)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                SqlCeCommand cmd = new SqlCeCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlCeDataAdapter da = new SqlCeDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlServerCe.SqlCeException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                    return ds;
                }
            }
        }

        private static void PrepareCommand(SqlCeCommand cmd, SqlCeConnection conn, SqlCeTransaction trans, string cmdText, SqlCeParameter[] 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 (SqlCeParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
        private static void PrepareCommand(SqlCeCommand cmd, SqlCeConnection conn, SqlCeTransaction trans, string cmdText, IDataParameter[] 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 (IDataParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        //public static OleDbDataReader Read_sql(string sql_str)//执行SQL语句——读取——返回Reader对象——它可以用作数据源的
        //{  
        //    OleDbConnection conn = Get_conn();
        //    OleDbDataReader read = null;
        //    OleDbCommand com = new OleDbCommand(sql_str,conn );//创建一个OleDbCommand对象,用于执行SQL语句
        //    com.CommandText = sql_str;
        //    //try
        //    //{
        //        conn.Open();
        //        read = com.ExecuteReader();//执行SQL语句,生成Reader对象
        //        conn.Close();

        //    //}
        //    //catch
        //    //{
        //    //    conn.Dispose();
        //    //}
        //    //#if  TEST
        //    //while (read.Read())
        //    //{
        //    //    foreach (int i in read)
        //    //        Console.WriteLine(read[i]);
        //    //}
        //        //#endif
        //    return read;//返回读取到的结果集
        //}

        //public DataView View_sql(string sql) //执行SQL语句——读取——返回DataView对象
        //{
        //    DataSet ds = new DataSet();
        //    ds = Get_DataSet(sql);
        //    DataView dv = new DataView(ds.Tables[0]);
        //    return dv;           
        //}
        #endregion

        #region 执行 返回受影响的行数
        /// <summary>
        /// 执行单条SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                SqlCeCommand cmd = new SqlCeCommand(SQLString, connection);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlServerCe.SqlCeException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        public static int ExecuteCmd(SqlCeCommand cmd)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                cmd.Connection = connection;
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlServerCe.SqlCeException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 执行单条带参数的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, IDataParameter[] parameters)
        {
            using (SqlCeConnection connection = GetConnection())
            {
                SqlCeCommand command = new SqlCeCommand(SQLString, connection);
                command.CommandType = CommandType.Text;
                //传入参数
                foreach (SqlCeParameter parameter in parameters)
                {
                    if (parameter != null)
                    {
                        // 检查未分配值的输出参数,将其分配以DBNull.Value.
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        command.Parameters.Add(parameter);
                    }
                }
                try
                {
                    connection.Open();
                    int rows = command.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlServerCe.SqlCeException e)
                {
                    throw e;
                }
                finally
                {
                    command.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>   
        /// <returns>int影响的记录数</returns>
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (SqlCeConnection conn = GetConnection())
            {
                conn.Open();
                SqlCeCommand cmd = new SqlCeCommand();
                cmd.Connection = conn;
                SqlCeTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }
        /// <summary>
        /// 执行存储过程,返回受影响行数
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>int影响的记录数</returns>
        public static int ExecuteProcedure(string procedureName, IDataParameter[] parameters)//执行存储过程——添加、删除、修改(存储过程名称,)
        {
            int count = 0;
            SqlCeConnection connection = GetConnection();
            SqlCeCommand command = new SqlCeCommand(procedureName, connection);//根据要执行的SQL语句和已有的数据库链接来创建一个OleDbCommand对象
            command.CommandType = CommandType.StoredProcedure;//使用存储过程
            //传入参数
            foreach (SqlCeParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            connection.Open();
            count = command.ExecuteNonQuery();//执行(对数据有更改的)
            command.Dispose();//释放
            connection.Close();
            return count;
        }

        #endregion

        #endregion
    }
}

你可能感兴趣的:(熙熙-SQLCE类-熙熙)