namespace TagTools
{
using System;
using System.Data;
using System.Data.SqlClient;
public class SqlHelper
{
public static string DBString = string.Empty;
public static int ExecuteNonQuery(string sql, CommandType commandType, params SqlParameter[] sqlp)
{
using (SqlConnection connection = new SqlConnection(DBString))
{
SqlCommand command = new SqlCommand(sql, connection) {
CommandType = commandType
};
if ((sqlp != null) && (sqlp.Length > 0))
{
command.Parameters.AddRange(sqlp);
}
connection.Open();
int num = command.ExecuteNonQuery();
if (connection.State == ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
return num;
}
}
public static SqlDataReader ExecuteReader(SqlConnection sqlConnection, string sql, CommandType commandType, params SqlParameter[] sqlp)
{
if (sqlConnection == null)
{
throw new ArgumentNullException("sqlConnection");
}
sqlConnection = new SqlConnection(DBString);
SqlCommand command = new SqlCommand(sql, sqlConnection) {
CommandType = commandType
};
if ((sqlp != null) && (sqlp.Length > 0))
{
command.Parameters.AddRange(sqlp);
}
sqlConnection.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
public static object ExecuteScalar(string sql, CommandType commandType, params SqlParameter[] sqlp)
{
using (SqlConnection connection = new SqlConnection(DBString))
{
object obj2;
SqlCommand command = new SqlCommand(sql, connection) {
CommandType = commandType
};
if ((sqlp != null) && (sqlp.Length > 0))
{
command.Parameters.AddRange(sqlp);
}
try
{
connection.Open();
obj2 = command.ExecuteScalar();
}
catch (Exception)
{
obj2 = 0;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
}
return obj2;
}
}
public static DataTable GetDataTable(string sql, CommandType commandType, params SqlParameter[] sqlp)
{
using (SqlConnection connection = new SqlConnection(DBString))
{
DataTable dataTable = new DataTable();
SqlCommand selectCommand = new SqlCommand(sql, connection) {
CommandType = commandType
};
if ((sqlp != null) && (sqlp.Length > 0))
{
selectCommand.Parameters.AddRange(sqlp);
}
connection.Open();
new SqlDataAdapter(selectCommand).Fill(dataTable);
if (connection.State == ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
return dataTable;
}
}
}
}
网友评论