第三周学习笔记
SqlHelper的主要知识点及应用
- 主要概念
他是使用ADO.Net方法对SQL Server数据库进行操作的封装类。是一个包含优化数据访问代码的.NET组件,我们所主要学习的一类为SqlHelper,SqlHelper 类提供了一组静态方法,可以用来向 SQL Server 数据库发出许多各种不同类型的命令, 使用方法有Command()、Scalar()、NonQuery()等。另一类了为SqlHelperParameterCache,SqlHelperParameterCache 类提供命令参数缓存功能,可以用来提高性能。该类由许多 Execute 方法在内部使用。
- 思维导图
- 例子
在作出如下界面
-
SqlHelper.cs输入如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
static class SqlHelper
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
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 object Scalar(string commandText, bool isStoredProcedure, SqlParameter[] sqlParameters)
{
object result = null;
using (SqlCommand sqlCommand = GetCommand(commandText, isStoredProcedure, sqlParameters))
{
sqlCommand.Connection.Open();
result = sqlCommand.ExecuteScalar();
sqlCommand.Connection.Close();
}
return result;
}
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
-
- 总结
在sqlhelper的使用中,对于合理的使用还是一件十分困难的问题,中间还是会碰到挺大的困难,以至于现在仍然没有很好的解决,如果能够合理的使用将会成为一个比较有用的帮助工具,同时在调用类方法上出错的地方还是很多。