-
6.2.7
数据库操作类
DBBase
简介和使用
DBBase
简介
< br>前面几节我们主要介绍了
的基本内容,
< br>对于数据库连接和数据的操作等常用
的方法,
总是重复的
编写大大的延缓了开发进度,
所以我们一些常用的方法封装成数据库操
< br>作类
DBBase
。
DBBas
e
既封装了数据库的连接操作以及数据库的查询、添加、删除和修改
等操作,
又包含了存储过程和事务的使用。
使用
DBBase
不仅可以大大的减少代码的重复编
写
,提高代码的重用性,缩短开发周期,而且有利于代码的维护和管理。
(
1
)
p>
Exists
方法
功能:
Exists
函数执行
SQL
语句,检索查询的信息是否存在,结果
返回
bool
值
参数:
strSql
是
SQL
p>
语句字符串
返回值:值为
false
则表示不存在
值为<
/p>
true
则表示存在
Exists
函数具体代码如下:
public static bool Exists(string
strSql)
{
using
(SqlConnection connection = new
SqlConnection(connectionString))
{
();
SqlCommand myCmd = new
SqlCommand(strSql, connection);
try
{
object obj = eScalar();
//
返回结果的第一行一列
();
p>
//
判断
SQL
语
句是否为空
if(((obj,null))||((obj,
)))
{
return
false;//
未找到相关信息,返回
false
}
else
{
return
true;//
返回
ture
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Exists
方法的使用
举例:学生登录时到
tbStudent
表(注:
本节中的所有例子都以选课系统中的学生表来演
示)判断学生登录名和密码是否正确
p>
,
其实现的主要代码
:
string sqlText =
where sno='
and
spwd='
//
若<
/p>
tag
值为
true
表示用户信息正确,若为
false
则为错误
bool tag = (sqlText);
(
2
p>
)
ExecuteSql
函数
功能:
Execute
Sql
函数主要执行
UPDATE
、<
/p>
INSERT
、
DELETE
等
SQL
语句,结果返回
影响的记录数。
参数:
strSql
是
SQL
语句字符串
< br>
返回值:值为整型数据表示影响的记录数
ExecuteSql
函数具体代码如下:
public static int ExecuteSql(string
SQLString)
{
//
每个方法增加带连接字符串的重载
SqlConnection connection = null;
SqlCommand cmd = null;
try
{
connection = new SqlConnect
ion(connectionString);//
创建连接
cmd = new SqlCommand(SQLString, connect
ion);//
创建
Command
对
象
();
int rows =
eNonQuery(); //
执行
SQL
< br>语句,保存影响记录数
return rows;
//
返回影响记录数
}
finally
{
if (cmd != null)//
判断
< br>cmd
是否存在
{
e();
}
if
(connection != null)
{
();//
关闭连接
e();
}
}
ExecuteSql
函数使用方法
p>
举例:更新
tbStudent
表中学号为
1
的学生的姓名、性别、班级、系别、密码等信息,其
使用的主要代码如下:
string sqlText =
+ sname +
+
ssex+
+ sclass +
+ sdept +
+
spwd+
int count = eSql(sqlText);
//count
的值表示更新的记录数
(
p>
3
)
ExecuteReader
函数
功能:
ExecuteSql
函数主要执行
SQL<
/p>
查询语句,结果返回
SqlDataReader
对象参数:
strSql
是
SQL
查询语句字符串。
返回值:返回值为
SqlDataReader
对象
ExecuteReader
p>
函数具体代码如下:
public static SqlDataReader
ExecuteReader(string strSQL)
{
SqlConnection connection = new
SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL,
connection);
try
{
();
SqlDataReader myReader = eReader
(onnection);
return myReader;
}
catch (eption e)
{
throw e;
}
finally
{
();
}
}
ExecuteSql
函数使用方法:
举例:
查询学生表
tbStudent
中的所有学生的信息并以
SqlData
Reader
对象形式返回,
其使用的主
要代码如下:
string sqlText
=