一、思维导图
二、知识点
sqlhelper是一个类,在这个类当中可以声明定义许多方法,如获取SQL命名、查询标量、写入操作等,sqlhelper可以用于简化重复的去写那些数据库连接(DbConnection),DbCommand,DbDataReader等等。SqlHelper 封装过后通常是只需要给方法传入一些参数如数据库连接字符串,SQL参数等,就可以访问数据库了,很方便。数据访问层可以通过调用SqlHelper当中的方法来实现一系列操作
总的来说SQLHelper类的作用就是代替每一个功能中连接数据库的过程的代码的,把那些代码给抽象出来封装,然后给其他的功能复用,达到代码简化的目的,但连接数据库的字符串也不是直接就写在了类里面,而是通过配置文件,把链接字符串在配置文件里写了。
三、示例
public class SqlHelper
{
private static SqlCommand GetCommand(string commandText, bool isStoredProcedure, SqlParameter[] sqlParameters)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Sql"].ToString();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = commandText;
if (isStoredProcedure)
{
sqlCommand.CommandType = CommandType.StoredProcedure;
}
if (sqlParameters != null)
{
sqlCommand.Parameters.AddRange(sqlParameters);
}
return sqlCommand;
}
public static int ExcuteNonQuery(string commandText, bool isStoredProcedure, SqlParameter[] sqlParameters)
{
int k=0;
using (SqlCommand sqlCommand = GetCommand(commandText, isStoredProcedure, sqlParameters))//调用GetCommand方法,避免了重复地敲响连接和命令的代码,使程序变得更简洁
{
sqlCommand.Connection.Open();
rowAffected = sqlCommand.ExecuteNonQuery();//执行命令
sqlCommand.Connection.Close();
}
return k;
}
}