本系列文章导航
基于.NET平台的Windows编程实战(一)——前言
基于.NET平台的Windows编程实战(二)—— 需求分析与数据库设计
基于.NET平台的Windows编程实战(四)—— 数据库操作类的编写
基于.NET平台的Windows编程实战(五)—— 问卷管理功能的实现
基于.NET平台的Windows编程实战(六)—— 题目管理功能的实现
					大家都知道本系统的正常运行少不了数据库操作这一块,且其在本系统中具有决定性作用,可以说没有它的操作系统将无法运行,故在本节课程中,专门把针对数据库的操作类拿出来讲讲,以便大家更加容易理解后面的课程。
好,进入正题……
首先,我们来新建一个类,方法如下:
打开上一节课我们新建的QuestionnaireSystem项目,右击项目名,在出现的对话框中选择“添加”à“类”,在弹出的“添加新项”中选择“类”,并在下面的“名称”中输入“DbOperate”,点“添加”,如下图4-1所示:
![]()
 
OK,这样我们的DbOperate类文件就创建好了,但里面还是空白的,所以我们下面就一起来编写相应的方法吧。
既然要对数据库进行操作,我们先要做的第一件事当然是要写个方法来打开数据库了。因为我们用的是Access2003数据库,所以我们得首先要using 进一个System.Data.OleDb 类库及一个System.Data 类库,方法:在新建的DbOperate文件的最上面,也就是写有几个using …… 地方,写入如下内容:
 
using System.Data;
using System.Data.OleDb;
 
其次,我们需要定义如下二个数据库操作对象:
 
protected OleDbConnection dbconn;//定义数据库连接对象
protected OleDbCommand dbcomm = new OleDbCommand();//定义数据库操作对象 
 
接下来,我们再写一个打开数据库连接的方法:
 
/// <summary>
        /// 打开数据库
         /// </summary>
        /// <returns></returns>
        protected void CreateDbConn()
        {
            try
            {//捕获连接异常
                string dbpath = @"DataBase\Lj_QuestionnaireSys.mdb";//设置数据库路径,如连接有问
题请在前面加上"..\..\",但在发布时要去掉前面的"..\..\"
                dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=
" + dbpath);//初始化数据库连接对象
                dbcomm.Connection = dbconn;//设置数据库操作对象使用此dbconn对象
                dbconn.Open();//打开数据库连接
            }
            catch (OleDbException) //如果出现数据库连接异常,则关闭数据库连接并弹出提示框
            {
                this.CloseDbConn();//关闭数据库连接
                MessageBox.Show("数据连接错误!可能是数据库被删除了11,请联系相关技术人员!", "操作提示", 
MessageBoxButtons.OK, MessageBoxIcon.Information);
                // Console.Write(dbex.Message);
            }
            catch (Exception) //如果出现其他异常,则关闭数据库连接并弹出提示框
            {
                this.CloseDbConn(); //关闭数据库连接
                MessageBox.Show("数据连接错误!可能是数据库被删除了,请联系相关技术人员!", "操作提示", 
MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 
 
数据库打开了,总不能让其长期开着吧!故我们还得写一关闭的方法:
 
        /// 关闭数据库
        /// 
        protected void CloseDbConn()
        {
            if (dbconn.State == ConnectionState.Open) //如果数据库为打开状态,则关闭
            {
                dbconn.Close();//关闭数据库连接
            }
            dbconn.Dispose();//释放连接资源
            dbcomm.Dispose();//释放操作资源
        }
 
 
 
 
好,至此,“开门”[打开数据库]与“关门”[关闭数据库]的方法都搞定了,下面就让我们设法在“开门”后“关门”前偷偷的躲进去做点实事吧,即写一些方法来读取或更新数据:
 
![]()
![]() Code
Code
![]()
![]() /**////
        /**//// 
![]() /// 执行SQL语句
        /// 执行SQL语句
![]() ///
        /// 
![]() /// 传入的SQL语句
        /// 传入的SQL语句
![]() public void ExcuteSql(string sqlText)
        public void ExcuteSql(string sqlText)
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型为文本类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型为文本类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() dbcomm.ExecuteNonQuery();//执行操作
                dbcomm.ExecuteNonQuery();//执行操作
![]() }
            }
![]() catch (Exception) //如果出现异常,则提示错误
            catch (Exception) //如果出现异常,则提示错误
![]()
![]() 
            ![]() {
{
![]() MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            }
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 判断是否执行成功,返回所影响的行数
        /// 判断是否执行成功,返回所影响的行数
![]() ///
        /// 
![]() /// 传入的SQL语句
        /// 传入的SQL语句
![]() /// 影响的行数
        /// 影响的行数
![]() public int ExcuteIntSql(string sqlText)
        public int ExcuteIntSql(string sqlText)
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() return dbcomm.ExecuteNonQuery();//执行操作,并返回影响的行数
                return dbcomm.ExecuteNonQuery();//执行操作,并返回影响的行数
![]() }
            }
![]() catch (Exception)
            catch (Exception) 
![]()
![]() 
            ![]() {
{
![]() //MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() return 0;//如果出现异常,则返回0
                return 0;//如果出现异常,则返回0
![]() 
              
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            } 
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 返回查询出的单条数字记录结果
        /// 返回查询出的单条数字记录结果
![]() ///
        /// 
![]() /// 传入的SQL语句
        /// 传入的SQL语句
![]() /// 查询出的数字结果
        /// 查询出的数字结果
![]() public int ExcuteScrSql(string sqlText)
        public int ExcuteScrSql(string sqlText)
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() return Convert.ToInt32(dbcomm.ExecuteScalar());//执行操作,并返回查询出的结果
                return Convert.ToInt32(dbcomm.ExecuteScalar());//执行操作,并返回查询出的结果
![]() }
            }
![]() catch (Exception)
            catch (Exception) 
![]()
![]() 
            ![]() {
{
![]() return 0;//如果出现异常,则返回0
                return 0;//如果出现异常,则返回0
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            }
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 返回查询出的单条文字记录结果
        /// 返回查询出的单条文字记录结果
![]() ///
        /// 
![]() /// 传入的SQL语句
        /// 传入的SQL语句
![]() /// 查询出的文字结果
        /// 查询出的文字结果
![]() public string ExcuteStrScrSql(string sqlText)
        public string ExcuteStrScrSql(string sqlText)
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() return dbcomm.ExecuteScalar().ToString();//执行操作,并返回查询出的结果
                return dbcomm.ExecuteScalar().ToString();//执行操作,并返回查询出的结果
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]() return "";//如果出现异常,则返回空字符串
                return "";//如果出现异常,则返回空字符串
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            }
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 返回查询出的数据表
        /// 返回查询出的数据表
![]() ///
        /// 
![]() /// 传入的SQL语句
        /// 传入的SQL语句
![]() /// 查询出的数据表
        /// 查询出的数据表
![]() public DataTable GetDataTable(string sqlText)
        public DataTable GetDataTable(string sqlText)
![]()
![]() 
        ![]() {
{
![]() OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
            OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
![]() DataTable dt = new DataTable();//实例化一个数据表
            DataTable dt = new DataTable();//实例化一个数据表
![]()
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() dbdapt.SelectCommand = dbcomm;//执行SQL语句,选择出数据
                dbdapt.SelectCommand = dbcomm;//执行SQL语句,选择出数据
![]() dbdapt.Fill(dt);//填充数据表
                dbdapt.Fill(dt);//填充数据表
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]()
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            }
![]() return dt;//返回查询出的数据表
            return dt;//返回查询出的数据表
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 按指定条数读出的Table数据表
        /// 按指定条数读出的Table数据表
![]() ///
        /// 
![]() /// 传入的SQL
        /// 传入的SQL
![]() /// 开始读数据的记录号
        /// 开始读数据的记录号
![]() /// 所要读出的最大条数
        /// 所要读出的最大条数
![]() /// 返回一数据表
        /// 返回一数据表
![]() public DataTable GetPageDataTable(string sqlText,int pre,int maxcunt)
        public DataTable GetPageDataTable(string sqlText,int pre,int maxcunt)
![]()
![]() 
        ![]() {
{
![]() OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
            OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
![]() DataSet ds = new DataSet();//实例化一个数据缓存器
            DataSet ds = new DataSet();//实例化一个数据缓存器
![]()
![]() try
            try
![]()
![]() 
            ![]() {//捕获异常
{//捕获异常
![]() CreateDbConn();//建立连接
                CreateDbConn();//建立连接
![]() dbcomm.CommandType = CommandType.Text;//设置操作类型
                dbcomm.CommandType = CommandType.Text;//设置操作类型
![]() dbcomm.CommandText = sqlText;//设置操作的SQL语句
                dbcomm.CommandText = sqlText;//设置操作的SQL语句
![]() dbdapt.SelectCommand = dbcomm;//执行操作,选择出数据
                dbdapt.SelectCommand = dbcomm;//执行操作,选择出数据
![]() dbdapt.Fill(ds,pre,maxcunt,"db_Table");//按指定的条数填充数据表
                dbdapt.Fill(ds,pre,maxcunt,"db_Table");//按指定的条数填充数据表
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]()
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseDbConn();//关闭连接
                CloseDbConn();//关闭连接
![]() }
            }
![]() return ds.Tables["db_Table"];//返回数据表
            return ds.Tables["db_Table"];//返回数据表
![]() }
        }
![]() //以下为合并统计的数据库操作 以下注释同上面的差不多,就不再写了
//以下为合并统计的数据库操作 以下注释同上面的差不多,就不再写了
![]() OleDbConnection conn;
        OleDbConnection conn;
![]() OleDbCommand comm = new OleDbCommand();
        OleDbCommand comm = new OleDbCommand();
![]()
![]() /**////
        /**//// 
![]() /// 连接数据库--合并统计用
        /// 连接数据库--合并统计用
![]() ///
        /// 
![]() public void DbConn()
        public void DbConn()
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {
{ 
![]() string _dbpath = @"DataBase\1.mdb";
                string _dbpath = @"DataBase\1.mdb";
![]() conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _dbpath);
                conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _dbpath);
![]() comm.Connection = conn;
                comm.Connection = conn;
![]() conn.Open();
                conn.Open();
![]() //MessageBox.Show(_dbpath);
                //MessageBox.Show(_dbpath);
![]() }
            }
![]() catch (OleDbException)
            catch (OleDbException)
![]()
![]() 
            ![]() {
{
![]() CloseConn();
                CloseConn();
![]() MessageBox.Show("数据库连接错误!请检查数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("数据库连接错误!请检查数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]() CloseConn();
                CloseConn();
![]() MessageBox.Show("数据库连接错误!请检查数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("数据库连接错误!请检查数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() }
            }
![]()
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 关闭数据库--合并统计用
        /// 关闭数据库--合并统计用
![]() ///
        /// 
![]() public void CloseConn()
        public void CloseConn()
![]()
![]() 
        ![]() {
{
![]() if (conn.State == ConnectionState.Open)
            if (conn.State == ConnectionState.Open)
![]()
![]() 
            ![]() {
{
![]() conn.Close();
                conn.Close();
![]() }
            }
![]() conn.Dispose();
            conn.Dispose();
![]()
![]() comm.Dispose();
            comm.Dispose();
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 返回数据表--合并统计用
        /// 返回数据表--合并统计用
![]() ///
        /// 
![]() ///
        /// 
![]() ///
        /// 
![]() public DataTable GetTable(string sqlText)
        public DataTable GetTable(string sqlText)
![]()
![]() 
        ![]() {
{
![]() OleDbDataAdapter odbad = new OleDbDataAdapter();
            OleDbDataAdapter odbad = new OleDbDataAdapter();
![]() DataTable dt = new DataTable();
            DataTable dt = new DataTable();
![]() try
            try
![]()
![]() 
            ![]() {
{
![]() DbConn();
                DbConn();
![]() comm.CommandType = CommandType.Text;
                comm.CommandType = CommandType.Text;
![]() comm.CommandText = sqlText;
                comm.CommandText = sqlText;
![]() odbad.SelectCommand = comm;
                odbad.SelectCommand = comm;
![]() odbad.Fill(dt);
                odbad.Fill(dt);
![]() }
            }
![]() catch (OleDbException)
            catch (OleDbException)
![]()
![]() 
            ![]() {
{
![]() MessageBox.Show("数据库连接错误!请选择正确的数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("数据库连接错误!请选择正确的数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]() MessageBox.Show("数据库连接错误!请选择正确的数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("数据库连接错误!请选择正确的数据库!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseConn();
                CloseConn();
![]() }
            }
![]() return dt;
            return dt;
![]() }
        }
![]()
![]() /**////
        /**//// 
![]() /// 返回查询的结果(Int)--合并统计用
        /// 返回查询的结果(Int)--合并统计用
![]() ///
        /// 
![]() /// 传入的SQL
        /// 传入的SQL
![]() /// Int
        /// Int
![]() public int ExcueteIntSql(string sqlText)
        public int ExcueteIntSql(string sqlText)
![]()
![]() 
        ![]() {
{
![]() try
            try
![]()
![]() 
            ![]() {
{
![]() DbConn();
                DbConn();
![]() comm.CommandText = sqlText;
                comm.CommandText = sqlText;
![]() return Convert.ToInt32(comm.ExecuteScalar());
                return Convert.ToInt32(comm.ExecuteScalar());
![]() }
            }
![]() catch (Exception)
            catch (Exception)
![]()
![]() 
            ![]() {
{
![]() return 0;
                return 0;
![]() }
            }
![]() finally
            finally
![]()
![]() 
            ![]() {
{
![]() CloseConn();
                CloseConn();
![]() }
            }
![]()
![]() }
        }
![]()
 
OK!到此,整个类算是完工了,虽然不好[没进行性能方面的优化,也没引入存储过程的操作等等],但对于基本的操作已经够用的了,故在此不作这方面的讨论;
    在后期的其它系列课程中,我打算专门写一系列针对数据库操作优化类的课程,到那时我们再拿出来一起讨论^_^
本课就先到此吧,谢谢……
附,本课程源码下载