public class SqlHelper
{
private static readonly string SqlConnStr = AppConfig.SqlConnStr;
//查询DT
public static DataTable QueryDataTable(string sql, object param = null)
{
SqlConnection conn = null;
SqlCommand sqlCommand = null;
SqlDataReader sqlDataReader = null;
try
{
conn = new SqlConnection(SqlConnStr);
conn.Open();
sqlCommand = new SqlCommand(sql, conn);
if (param != null) AddParam(sqlCommand, param);
sqlDataReader = sqlCommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sqlDataReader);
return dt;
}
catch (Exception e)
{
LogHelper.AddLog($"Sql查询异常:{e.Message} [{sql}]");
return null;
}
finally
{
sqlDataReader?.Dispose();
sqlCommand?.Dispose();
conn?.Close();
}
}
public static int Excute(string sql, object param = null)
{
SqlConnection conn = null;
SqlCommand sqlCommand = null;
try
{
conn = new SqlConnection(SqlConnStr);
sqlCommand = new SqlCommand(sql, conn);
if (param != null) AddParam(sqlCommand, param);
conn.Open();
return sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
LogHelper.AddLog($"Sql操作异常:{e.Message} [{sql}]");
return -1;
}
finally
{
sqlCommand?.Dispose();
conn?.Close();
}
}
//动态添加sql参数
private static void AddParam(SqlCommand sqlCommand, object param)
{
PropertyInfo[] properties = param.GetType().GetProperties();
int size = properties.Length;
if (size == 0) return;
for (int i = 0; i < size; i++)
{
PropertyInfo property = properties[i];
object value = property.GetValue(param);
string name = property.Name;
if (value != null && !string.IsNullOrEmpty(value.ToString()))
{
sqlCommand.Parameters.AddWithValue(name, value);
}else
{
sqlCommand.Parameters.AddWithValue(name, DBNull.Value);
}
}
}
}
**尝试过像Java一样转化为实体类,最后发现还是DataTable好用。