之前用过简单三层架构,三层架构在我看来是一套程序里的工程架构,便于程序上的分层,架构清晰。但是在编写代码过程中可能会有一定的复杂性。
生成三层架构的方法有很多,codesmith、动软都可以。今天用动软生成了一下,效果还可以,基本上能够满足简单.net程序的使用。但是生成之后,还需要对生成的代码进行一定的调试和修改,本身带有一些bug。codesmith需要自己写一些模板,还有待研究。
贴出一个动软6.5能够使用且比较完整的sqlhelper:
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Collections;
using System.Web;
namespace DBUtility
{
public abstract class SqlHelper
{
// Read the connection strings from the configuration file
public static readonly string SqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//public static readonly string SqlConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
//Create a hashtable for the parameter cached
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
protected static string ConnectionString
{
get { return SqlConnectionString; }
}
public static SqlConnection CreateCon()//做成静态变量,以后让此类以外的程序也能访问
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
#region 公用方法(获取ID最大值加1)
//==========================================
//对事务进行扩展
//==========================================
public static SqlTransaction CreateTrans(SqlConnection con)
{
SqlTransaction trans = con.BeginTransaction();//可扩展隔离级别
return trans;
}
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(cast (" + FieldName + " as int))+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
#endregion
///
/// 判断满足条件的记录是否存在
///
///
///
public static bool Exists2(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
object obj = SqlHelper.GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand2(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
}
}
}
///
/// execute the sql and return the count of line
///
///
///
public static int ExecuteNonQuery(string sql)
{
int count = -1;
if (String.IsNullOrEmpty(sql))
return count;
return ExecuteNonQuery(sql, (SqlParameter[])null);
}
public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
///
/// 执行sql语句
///
///
///
///
public static int ExecuteNonQuery(string sql, SqlParameter[] parameters)
{
CommandType commandType = CommandType.Text;
return ExecuteNonQuery(commandType, sql, parameters);
}
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand2(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
}
}
///
///
///
///
///
///
///
public static int ExecuteNonQuery(CommandType commandType, string commandText, SqlParameter[] parameters)
{
int count = -1;
if (string.IsNullOrEmpty(commandText) && parameters == null)
return count;
// Create a new Oracle command
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//Prepare the command
PrepareCommand(cmd, connection, null, commandType, commandText, parameters);
//Execute the command
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
///
/// Execute a database query which does not include a select
///
/// Connection string to database
/// Command type either stored procedure or SQL
/// Acutall SQL Command
/// Parameters to bind to the command
///
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
// Create a new Oracle command
SqlCommand cmd = new SqlCommand();
//Create a connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Prepare the command
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
//Execute the command
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
///
/// Execute an OracleCommand (that returns no resultset) against an existing database transaction
/// using the provided parameters.
///
///
/// e.g.:
/// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
///
/// an existing database transaction
/// the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
/// an int representing the number of rows affected by the command
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;
}
public static int ExecuteNonQuery(SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
///
/// Execute an OracleCommand (that returns no resultset) against an existing database connection
/// using the provided parameters.
///
///
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
///
/// an existing database connection
/// the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
/// an int representing the number of rows affected by the command
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;
}
///
/// Execute a select query that will return a result set
///
/// Connection string
the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
///
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
//Create the command and connection
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(ConnectionString);
try
{
//Prepare the command to execute
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
//Execute the query, stating that the connection should close when the resulting datareader has been read
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
//If an error occurs close the connection as the reader will not be used and we expect it to close the connection
conn.Close();
throw;
}
}
///
/// Execute a select query that will return a result set
///
/// Connection string
the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
///
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
//Create the command and connection
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
try
{
//Prepare the command to execute
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
//Execute the query, stating that the connection should close when the resulting datareader has been read
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
//If an error occurs close the connection as the reader will not be used and we expect it to close the connection
conn.Close();
throw;
}
}
///
/// Execute an OracleCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
///
///
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
///
/// a valid connection string for a SqlConnection
/// the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
/// An object that should be converted to the expected type using Convert.To{Type}
public static object ExecuteScalar(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);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
///
/// Execute a OracleCommand (that returns a 1x1 resultset) against the specified SqlTransaction
/// using the provided parameters.
///
/// A valid SqlTransaction
/// The CommandType (stored procedure, text, etc.)
/// The stored procedure name or PL/SQL command
/// An array of OracleParamters used to execute the command
/// An object containing the value in the 1x1 resultset generated by the command
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null)
throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null)
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
// Execute the command & return the results
object retval = cmd.ExecuteScalar();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
///
/// Execute an OracleCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
///
///
/// e.g.:
/// Object obj = ExecuteScalar(conn, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
///
/// an existing database connection
/// the CommandType (stored procedure, text, etc.)
/// the stored procedure name or PL/SQL command
/// an array of OracleParamters used to execute the command
/// An object that should be converted to the expected type using Convert.To{Type}
public static object ExecuteScalar(SqlConnection connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connectionString, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
///
/// Add a set of parameters to the cached
///
/// Key value to look up the parameters
/// Actual parameters to cached
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
///
/// Fetch parameters from the cache
///
/// Key to look up the parameters
///
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
// If the parameters are in the cache
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
// return a copy of the parameters
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
///
/// Internal function to prepare a command for execution by the database
///
/// Existing command object
/// Database connection object
/// Optional transaction object
/// Command type, e.g. stored procedure
/// Command test
/// Parameters for the command
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] commandParameters)
{
//Open the connection if required
if (conn.State != ConnectionState.Open)
conn.Open();
//Set up the command
cmd.Connection = conn;
cmd.CommandText = cmdText;
cmd.CommandType = cmdType;
//Bind it to the transaction if it exists
if (trans != null)
cmd.Transaction = trans;
// Bind the parameters passed in
if (commandParameters != null)
{
foreach (SqlParameter parm in commandParameters)
cmd.Parameters.Add(parm);
}
}
private static void PrepareCommand3(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
private static void PrepareCommand2(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
///
/// Converter to use boolean data type with Oracle
///
/// Value to convert
///
public static string OraBit(bool value)
{
if (value)
return "Y";
else
return "N";
}
///
/// Converter to use boolean data type with Oracle
///
/// Value to convert
///
public static bool OraBool(string value)
{
if (value.Equals("Y"))
return true;
else
return false;
}
#region ExecuteDataSet
public static DataSet ExecuteDataSet(string sql)
{
if (String.IsNullOrEmpty(sql))
return null;
return ExecuteDataSet(sql, (SqlParameter[])null);
}
///
///
///
///
///
///
public static DataSet ExecuteDataSet(string sql, params SqlParameter[] parameters)
{
if (string.IsNullOrEmpty(sql) && parameters == null)
return null;
return ExecuteDataSet(CommandType.Text, sql, parameters);
}
public static DataSet Query(string sql, params SqlParameter[] parameters)
{
if (string.IsNullOrEmpty(sql) && parameters == null)
return null;
return ExecuteDataSet(CommandType.Text, sql, parameters);
}
///
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
///
///
/// e.g.:
/// DataSet ds = ExecuteDataset( CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
///
/// A valid SqlConnection
/// The CommandType (stored procedure, text, etc.)
/// The stored procedure name or T-SQL command
/// An array of SqlParamters used to execute the command
/// A dataset containing the resultset generated by the command
public static DataSet ExecuteDataSet(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// Create a command and prepare it for execution
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
// Create the DataAdapter & DataSet
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// Fill the DataSet using default values for DataTable names, etc
da.Fill(ds);
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
connection.Close(); //添加byliu2010.10.28
// Return the dataset
return ds;
}
}
catch
{
connection.Close();
throw;
}
finally
{
connection.Dispose();
}
}
}
}
public static SqlConnection createCon()
{
string constr = @"server=(local);uid=sa;pwd=123;database=NJERP";
SqlConnection con = new SqlConnection(constr);
return con;
}
public static SqlDataReader getReader(string sql)
{
SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = createCon();
if (con.State != ConnectionState.Open)
con.Open();
cmd = new SqlCommand(sql, con);
return cmd.ExecuteReader();
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
#endregion
#region 存储过程操作
///
/// 执行存储过程
///
/// 存储过程名
/// 存储过程参数
/// SqlDataReader
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
SqlDataReader returnReader;
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.CommandType = CommandType.StoredProcedure;
returnReader = command.ExecuteReader();
return returnReader;
}
///
/// 执行存储过程
///
/// 存储过程名
/// 存储过程参数
/// DataSet结果中的表名
/// DataSet
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
///
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
///
/// 数据库连接
/// 存储过程名
/// 存储过程参数
/// SqlCommand
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
return command;
}
///
/// 执行存储过程,返回影响的行数
///
/// 存储过程名
/// 存储过程参数
/// 影响的行数
///
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
int result;
connection.Open();
SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
//Connection.Close();
return result;
}
}
///
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
///
/// 存储过程名
/// 存储过程参数
/// SqlCommand 对象实例
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
//==========================================
//运行存储过程
//==========================================
public static int RunProcedure(SqlConnection conn, SqlTransaction trans, string StoredProName, SqlParameter[] parameters) //添加byliu2010.10.23
{
int intNumber = 0;
SqlCommand cmd = new SqlCommand(StoredProName, conn);
cmd.Transaction = trans;
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
intNumber = cmd.ExecuteNonQuery();//执行存储过程
return intNumber;
}
#endregion
}
}