方法:
/// <summary>
/// 错误日志书写/// </summary>
/// <param name="sqlStr">发生错误的sql语句或者标记</param>
/// <param name="errorMessage">错误信息</param>
public static void ErrorLogPrint(string sqlStr, string errorMessage)
{
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\SuppliesManagementLog";
StringBuilder result = new StringBuilder("-----------------------------");
result.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
result.Append("---------------------------\r\n");
result.Append("发生错误的语句:");
result.Append(sqlStr);
result.Append("\r\n错误信息:");
result.Append(errorMessage);
if (!Directory.Exists(filePath))//文件所在路径不存在时 创建路径
{
Directory.CreateDirectory(filePath);
}
FileInfo fi = new FileInfo(filePath + @"\ErrorLog.txt");
if (!fi.Exists)//文件不存在时 创建文件
{
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine(result.ToString());
}
}
else
{
if (fi.Length >= 6000)//文件内容的长度大于一定范围时,清空
{
fi.Delete();
}
using (StreamWriter sw = fi.AppendText())
{
sw.WriteLine(result.ToString());
}
}
}
应用:
/// <summary>
/// 执行没有返回结果集的SQL语句
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(string sql)
{
try
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(ConnStr))
{
PrepareCommand(cmd, conn, null, 0, sql, null);
int val = cmd.ExecuteNonQuery();
return val;
}
}
catch (Exception ex)
{
PublicFunction.ErrorLogPrint(sql, ex.Message);
return 0;
}
}
/// <summary>
/// 执行SQL语句返回一个DataSet
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <returns>DataSet对象</returns>
public static DataSet ExecuteDataSet(string sql)
{
try
{
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
using (SqlConnection Conn = new SqlConnection(ConnStr))
{
PrepareCommand(cmd, Conn, null, 0, sql, null);
SqlDataAdapter dapter = new SqlDataAdapter(cmd);
dapter.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
catch (Exception ex)
{
PublicFunction.ErrorLogPrint(sql, ex.Message);
return null;
}
}