【ASP.NET】如何连接SQLServer
时间:2021-07-01 10:21:17
帮助过:8人阅读
System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
namespace ClientCheckWeb.Models
{
public class SqlHelper
{
//数据库连接字符串
private static string s_ConnectionString = "";
public static string ConnectionString
{
get
{
if (string.IsNullOrEmpty(s_ConnectionString))
{
string conStr = ConfigurationManager.ConnectionStrings["DbConnectionStr"].ConnectionString;
int pos = conStr.IndexOf(";pwd=");
string txt1 = conStr.Substring(0, pos);
string txt2 = conStr.Substring(pos + 5);
conStr = txt1 + ";pwd=" + Sam.Common.Security.Decrypt(txt2);
string conStr_lower = conStr.ToLower();
string wUser = "Trusted_Connection";
if (conStr_lower.IndexOf(wUser.ToLower()) >= 0)
{
s_ConnectionString = "error";
}
else
{
s_ConnectionString = conStr;
}
}
return s_ConnectionString;
}
}
// Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
private static object ReadValue(SqlDataReader reader, string fName, TypeCode typeCode)
{
object value = null;
int fOrder = -1;
try
{
fOrder = reader.GetOrdinal(fName);
}
catch (Exception ex)
{
}
value = ReadValue(reader, fOrder, typeCode);
return value;
}
private static object ReadValue(SqlDataReader reader, int fOrder, TypeCode typeCode)
{
object value = null;
if (fOrder < 0)
{
}
else if (reader.IsDBNull(fOrder))
{
}
else if (typeCode == TypeCode.String)
{
value = reader.GetString(fOrder);
}
else if (typeCode == TypeCode.Int16)
{
value = reader.GetInt16(fOrder);
}
else if (typeCode == TypeCode.Int32)
{
value = reader.GetInt32(fOrder);
}
else if (typeCode == TypeCode.Int64)
{
value = reader.GetInt64(fOrder);
}
else if (typeCode == TypeCode.DateTime)
{
value = reader.GetDateTime(fOrder);
}
else if (typeCode == TypeCode.Boolean)
{
value = reader.GetBoolean(fOrder);
}
else if (typeCode == TypeCode.Decimal)
{
value = reader.GetDecimal(fOrder);
}
else if (typeCode == TypeCode.Double)
{
value = reader.GetDouble(fOrder);
}
else if (typeCode == TypeCode.Byte)
{
value = reader.GetByte(fOrder);
}
else
{
string str = typeCode.ToString();
int i = 0;
}
return value;
}
public static T DoQueryFirstField<T>(string sql, T defValue, params SqlParameter[] commandParameters)
{
T result = defValue;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlDataReader reader = ExecuteReader(connection, CommandType.Text, sql, commandParameters);
if (reader.Read())
{
Type type = result.GetType();
TypeCode typeCode = Type.GetTypeCode(type);
object value = ReadValue(reader, 0, typeCode);
if (value != null)
{
result = (T)value;
}
}
reader.Dispose();
}
return result;
}
public static List<T> DoQuery<T>(string sql, params SqlParameter[] commandParameters)
{
List<T> list = new List<T>();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlDataReader reader = ExecuteReader(connection, CommandType.Text, sql, commandParameters);
while (reader.Read())
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
foreach (FieldInfo fi in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
string fName = fi.Name;
TypeCode typeCode = Type.GetTypeCode(fi.FieldType);
object value = ReadValue(reader, fName, typeCode);
if (value != null)
{
fi.SetValue(obj, value);
}
}
foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
string fName = pi.Name;
TypeCode typeCode = Type.GetTypeCode(pi.PropertyType);
object value = ReadValue(reader, fName, typeCode);
if (value != null)
{
pi.SetValue(obj, value, null);
}
}
list.Add(obj);
}
reader.Dispose();
}
return list;
}
/// <summary>
///执行SQL语句,返回受影响的行数
/// </summary>
/// <param name="cmdType">命令类型:文本语句、存储过程</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteNonQuery(ConnectionString, cmdType, cmdText, commandParameters);
}
/// <summary>
/// 执行SQL语句,返回受影响的行数(默认按文本查询类型执行)
/// </summary>
/// <param name="cmdText">语句内容</param>
/// <param name="commandParameters">查询参数</param>
/// <returns></returns>
public static int ExecuteNonQuery(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteNonQuery(ConnectionString, CommandType.Text, cmdText, commandParameters);
}
/// <summary>
/// 执行SQL语句,返回受影响的行数
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// 执行SQL语句,返回受影响的行数
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行SQL语句,返回受影响的行数。需要事务控制
/// </summary>
/// <param name="trans">事务管理对象</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行SQL语句返回数据结果集
/// </summary>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>数据结果集</returns>
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteReader(ConnectionString, cmdType, cmdText, commandParameters);
}
public static SqlDataReader ExecuteReader(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteReader(ConnectionString, CommandType.Text, cmdText, commandParameters);
}
/// <summary>
/// 执行SQL语句返回数据结果集
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>数据结果集</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
}
/// <summary>
/// 执行SQL语句返回数据结果集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>数据结果集</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader();
cmd.Parameters.Clear();
return rdr;
}
/// <summary>
/// 执行SQL语句返回第一行第一列内容
/// </summary>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>第一行一列的值通过Convert.To{Type}转化成相应类型</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(ConnectionString, cmdType, cmdText, commandParameters);
}
public static object ExecuteScalar(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteScalar(ConnectionString, CommandType.Text, cmdText, commandParameters);
}
/// <summary>
/// 执行SQL语句返回第一行第一列内容
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>第一行一列的值通过Convert.To{Type}转化成相应类型</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// 执行SQL语句返回第一行第一列内容
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>第一行一列的值通过Convert.To{Type}转化成相应类型</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行SQL语句返回第一行第一列内容
/// </summary>
/// <param name="trans">事务管理对象</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <param name="commandParameters"></param>
/// <returns>第一行一列的值通过Convert.To{Type}转化成相应类型</returns>
public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行SQL语句返回内存数据表
/// </summary>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>内存数据表</returns>
public static DataTable ExecuteTable(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteTable(ConnectionString, cmdType, cmdText, commandParameters);
}
public static DataTable ExecuteTable(string cmdText, params SqlParameter[] commandParameters)
{
return ExecuteTable(ConnectionString, CommandType.Text, cmdText, commandParameters);
}
/// <summary>
/// 执行查询的SQL语句返回内存数据表
/// </summary>
/// <param name="connectionString">数据库连接串</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>内存数据表</returns>
public static DataTable ExecuteTable(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
SqlDataAdapter ap = new SqlDataAdapter();
ap.SelectCommand = cmd;
DataSet st = new DataSet();
ap.Fill(st, "Result");
cmd.Parameters.Clear();
return st.Tables["Result"];
}
}
/// <summary>
/// 执行SQL语句返回内存数据表
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdText">执行文本串</param>
/// <param name="commandParameters">查询参数</param>
/// <returns>内存数据表</returns>
public static DataTable ExecuteTable(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
SqlDataAdapter ap = new SqlDataAdapter();
ap.SelectCommand = cmd;
DataSet st = new DataSet();
ap.Fill(st, "Result");
cmd.Parameters.Clear();
return st.Tables["Result"];
}
#region 添加参数数组到缓存Hashtable中
/// <summary>
///添加参数数组到缓存Hashtable中
/// </summary>
/// <param name="cacheKey">Hashtable中的KEY值</param>
/// <param name="commandParameters">参数数组</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
#endregion
#region 复制方式获取缓存Hashtable中的参数数组
/// <summary>
/// 复制方式获取缓存Hashtable中的参数数组
/// </summary>
/// <param name="cacheKey">Hashtable中的KEY值</param>
/// <returns>参数数组</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
#endregion
#region 组织Sql查询对象的关系
/// <summary>
/// 组织Sql查询对象的关系(包括参数设置)
/// </summary>
/// <param name="cmd">Sql查询对象</param>
/// <param name="conn">数据库连接对象</param>
/// <param name="trans">事务对象</param>
/// <param name="cmdType">查询类型</param>
/// <param name="cmdText">查询语句</param>
/// <param name="cmdParms">参数数组</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
/// <summary>
/// 执行对默认数据库有自定义排序的分页的查询
/// </summary>
/// <param name="SqlAllFields">查询字段,如果是多表查询,请将必要的表名或别名加上,如:a.id,a.name,b.score</param>
/// <param name="SqlTablesAndWhere">查询的表如果包含查询条件,也将条件带上,但不要包含order by子句,也不要包含"from"关键字,如:students a inner join achievement b on a.... where ....</param>
/// <param name="IndexField">用以分页的不能重复的索引字段名,最好是主表的自增长字段,如果是多表查询,请带上表名或别名,如:a.id</param>
/// <param name="OrderASC">排序方式,如果为true则按升序排序,false则按降序排</param>
/// <param name="OrderFields">排序字段以及方式如:a.OrderID desc,CnName desc</OrderFields>
/// <param name="PageIndex">当前页的页码</param>
/// <param name="PageSize">每页记录数</param>
/// <param name="RecordCount">输出参数,返回查询的总记录条数</param>
/// <param name="PageCount">输出参数,返回查询的总页数</param>
/// <returns>返回查询结果</returns>
public static DataTable ExecutePage(string SqlAllFields, string SqlTablesAndWhere, string IndexField, string OrderFields, int PageIndex, int PageSize, out int RecordCount, out int PageCount, params SqlParameter[] commandParameters)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
return ExecutePage(connection, SqlAllFields, SqlTablesAndWhere, IndexField, OrderFields, PageIndex, PageSize, out RecordCount, out PageCount, commandParameters);
}
}
/// <summary>
/// 执行有自定义排序的分页的查询
/// </summary>
/// <param name="connection">SQL数据库连接对象</param>
/// <param name="SqlAllFields">查询字段,如果是多表查询,请将必要的表名或别名加上,如:a.id,a.name,b.score</param>
/// <param name="SqlTablesAndWhere">查询的表如果包含查询条件,也将条件带上,但不要包含order by子句,也不要包含"from"关键字,如:students a inner join achievement b on a.... where ....</param>
/// <param name="IndexField">用以分页的不能重复的索引字段名,最好是主表的自增长字段,如果是多表查询,请带上表名或别名,如:a.id</param>
/// <param name="OrderASC">排序方式,如果为true则按升序排序,false则按降序排</param>
/// <param name="OrderFields">排序字段以及方式如:a.OrderID desc,CnName desc</OrderFields>
/// <param name="PageIndex">当前页的页码</param>
/// <param name="PageSize">每页记录数</param>
/// <param name="RecordCount">输出参数,返回查询的总记录条数</param>
/// <param name="PageCount">输出参数,返回查询的总页数</param>
/// <returns>返回查询结果</returns>
public static DataTable ExecutePage(SqlConnection connection, string SqlAllFields, string SqlTablesAndWhere, string IndexField, string OrderFields, int PageIndex, int PageSize, out int RecordCount, out int PageCount, params SqlParameter[] commandParameters)
{
RecordCount = 0;
PageCount = 0;
if (PageSize <= 0)
{
PageSize = 10;
}
if (connection.State !=