/// <summary> /// 构建数据库对象 /// </summary> /// <param name="server">服务器地址</param> /// <param name="database">数据库名称</param> /// <param name="userId">用户名</param> /// <param name="password">密码</param> /// <param name="poolSize">连接池连接数</param> /// <param name="consolePrintSql">是否在控制台输出Sql语句</param> public DbContext(string server, string database, string userId, string password, int poolSize = 3, bool consolePrintSql = false) { if (string.IsNullOrWhiteSpace(server) || string.IsNullOrWhiteSpace(database) || string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(password)) { throw new ConnectionStringIsEmptyException(); } if (consolePrintSql) { _consolePrintSql = true; } if (poolSize <= 0) { throw new ConnectionStringIsEmptyException($"连接数最小为一个!"); } string connectionString = BuildConnectionString(server, database, userId, password); SQLServerConnectionPools.Init(connectionString, poolSize); _dbSQLHelper = new SQLServerHelper(connectionString); }
public int ExecuteNonQuery(bool isNewConnection, bool consolePrintSql, string commandText, params IDbDataParameter[] parameters) { if (string.IsNullOrWhiteSpace(commandText)) { throw new ArgumentNullException("执行命令不能为空"); } int result = 0; if (isNewConnection == true) { using (IDbConnection connection = new SqlConnection(_connectionString)) { connection.Open(); result = ExecuteNonQuery(connection, consolePrintSql, commandText, parameters); } } else { using (IConnector connector = SQLServerConnectionPools.GetConnector()) { result = ExecuteNonQuery(connector.GetConnection(), consolePrintSql, commandText, parameters); } } return(result); }
public List <T> ExecuteList <T>(bool consolePrintSql, List <PropertyInfo> propertyInfoList, string commandText, params IDbDataParameter[] parameters) { if (string.IsNullOrWhiteSpace(commandText)) { throw new ArgumentNullException("执行命令不能为空"); } List <T> list = new List <T>(); using (IConnector connector = SQLServerConnectionPools.GetConnector()) { IDbCommand command = connector.GetConnection().CreateCommand(); command.CommandText = commandText; foreach (IDbDataParameter parameter in parameters) { command.Parameters.Add(parameter); } PrintSql(consolePrintSql, commandText); IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); list = InstanceFactory.CreateListAndDisposeReader <T>(reader, propertyInfoList); } return(list); }
public object ExecuteScalar(bool consolePrintSql, string commandText, params IDbDataParameter[] parameters) { if (string.IsNullOrWhiteSpace(commandText)) { throw new ArgumentNullException("执行命令不能为空"); } object result = null; using (IConnector connector = SQLServerConnectionPools.GetConnector()) { using (IDbCommand command = connector.GetConnection().CreateCommand()) { command.CommandText = commandText; foreach (IDbDataParameter parameter in parameters) { command.Parameters.Add(parameter); } PrintSql(consolePrintSql, commandText); result = command.ExecuteScalar(); } } return(result); }