SqlHelper用于简化你重复的去写那些数据库连接(SqlConnection),SqlCommand,SqlDataReader等等。SqlHelper 封装过后通常是只需要给方法传入一些参数如数据库连接字符串,SQL参数等,就可以访问数据库了,很方便。
思维导图如下:
先在config配置连接语句:
<connectionStrings>
<add name="Sql"
connectionString="Server=(local);Database=EduBaseHosp;uid=SqlLogin1;pwd=123"
providerName="System.Data.SqlClient"/>
</connectionStrings>
接着创建Sqlhelper类,代码如下:
public class SqlHelper
{
private static SqlCommand GetCommand(string commandText, SqlParameter[] sqlParameters)
{
SqlConnection sqlConnection = new SqlConnection(); //声明并实例化SQL连接;
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Sql"].ToString(); //配置管理器从App.config读取连接字符串;
SqlCommand sqlCommand = sqlConnection.CreateCommand(); //调用SQL连接的方法CreateCommand来创建SQL命令;该SQL命令将绑定SQL连接;
sqlCommand.CommandText = commandText; //指定SQL命令的命令文本;
if (sqlParameters != null) //若SQL参数数组非空;
{
sqlCommand.Parameters.AddRange(sqlParameters); //将SQL参数数组内的所有SQL参数,批量添加至SQL命令的参数集合;
}
return sqlCommand; //返回SQL命令;
}
public static object Scalar(string commandText, SqlParameter[] sqlParameters)
{
object result = null; //查询结果可能类型多样,故先声明对象,并指向空值;
using (SqlCommand sqlCommand = GetCommand(commandText, sqlParameters)) //调用SQL助手的静态方法GetCommand来创建SQL命令,并定义其作用范围;
{
sqlCommand.Connection.Open(); //打开SQL命令的连接;
result = sqlCommand.ExecuteScalar(); //调用SQL命令的方法ExecuteScalar来执行命令,并返回单个结果(即标量);
sqlCommand.Connection.Close(); //关闭SQL连接;
}
return result; //返回查询结果;
}
public static int NonQuery(string commandText, SqlParameter[] sqlParameters)
{
int rowAffected = 0; //声明整型变量,用于保存受影响行数;
using (SqlCommand sqlCommand = GetCommand(commandText, sqlParameters)) //调用SQL助手的静态方法GetCommand来创建SQL命令,并定义其作用范围;
{
sqlCommand.Connection.Open(); //打开SQL命令的连接;
rowAffected = sqlCommand.ExecuteNonQuery(); //调用SQL命令的方法ExecuteNonQuery来执行命令,向数据库写入数据,并返回受影响行数;
sqlCommand.Connection.Close(); //关闭SQL连接;
}
return rowAffected; //返回受影响行数;
}
}
接着创建一个窗体,一个文本框,一个按钮,调用它,如图窗体:
代码如下:
private void button2_Click(object sender, EventArgs e)
{
string commandText = "select *from tb_Student where No=@No";
SqlParameter[] sqlParameters =
{ new SqlParameter("@No", textBox2.Text)
, };
if (SqlHelper.NonQuery(commandText, sqlParameters) == 1)
{
MessageBox.Show("查询成功");
}
}
运行结果: