底层sqlHelper

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;namespace WX_Card.CardDAL
{public class D_Helper{#region 日志信息/// <summary>/// 记录日志信息/// </summary>/// <param name="message">日志信息</param>public static void WriteBarcodesLog(string message){if (string.IsNullOrWhiteSpace(message))return;message = "【" + DateTime.Now.ToString("HH:mm:ss") + "】" + message;try{string path = "";if (path == ""){path = "D:/LogFile/DAL_Log/";}if (!Directory.Exists(path)){Directory.CreateDirectory(path);}//文件名  //按天记录日志string fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";path += fileName;if (File.Exists(path)){System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Append);System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);try{sw.WriteLine(message);sw.Close();fs.Close();}catch{sw.Close();fs.Close();}}else{System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);try{sw.WriteLine(message);sw.Close();fs.Close();}catch{sw.Close();fs.Close();}}}catch{}}public static void WriteException(string msg){WriteBarcodesLog(msg, "exception");}/// <summary>/// 记录日志信息/// </summary>/// <param name="message">日志信息</param>public static void WriteBarcodesLog(string message, string fname){if (string.IsNullOrWhiteSpace(message))return;message = "【" + DateTime.Now.ToString("HH:mm:ss") + "】" + message;try{string path = "";if (path == ""){path = "D:/LogFile/DAL_Log/";}if (!Directory.Exists(path)){Directory.CreateDirectory(path);}//文件名  //按天记录日志string fileName = fname + DateTime.Now.ToString("yyyyMMdd") + ".txt";path += fileName;if (File.Exists(path)){System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Append);System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);try{sw.WriteLine(message);sw.Close();fs.Close();}catch{sw.Close();fs.Close();}}else{System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);try{sw.WriteLine(message);sw.Close();fs.Close();}catch{sw.Close();fs.Close();}}}catch{}}#endregion/// <summary>/// 运行SQL语句,返回DataSet/// </summary>/// <param name="SqlStr"></param>/// <returns></returns>public DataSet runSQLDataSet(string SqlStr){string connstr = WX_Card.CardDAL.Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = SqlStr;cm.CommandType = CommandType.Text;DataSet DS = null;try{SqlDataAdapter da = new SqlDataAdapter(cm);DS = new DataSet();da.Fill(DS);da.Dispose();}catch (Exception ex){throw ex;}finally{cm.Connection.Close();cm.Dispose();}return DS;}/// <summary>/// 执行sql语句返回受影响行数【放注入】/// </summary>/// <param name="sql"></param>/// <param name="paras"></param>/// <returns></returns>public  int GetDataRow(string sql, params SqlParameter[] paras){string connstr = WX_Card.CardDAL.Properties.Settings.Default.lswxConnectionString;DataTable dt = null;using (SqlConnection conn = new SqlConnection(connstr)){SqlCommand command = new SqlCommand(sql, conn);command.Parameters.AddRange(paras);SqlDataAdapter adapter = new SqlDataAdapter(command);dt = new DataTable();adapter.Fill(dt);}return dt.Rows.Count;}/// <summary>/// 运行SQL语句,返回DataTable/// </summary>/// <param name="SqlStr"></param>/// <returns></returns>public DataTable runSQLDataTable(string SqlStr){string connstr = Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = SqlStr;cm.CommandType = CommandType.Text;cm.CommandTimeout = 120;//超时时间设置为2分钟DataSet DS = null;try{SqlDataAdapter da = new SqlDataAdapter(cm);DS = new DataSet();da.Fill(DS);da.Dispose();}catch (Exception ex){throw ex;}finally{cm.Connection.Close();cm.Dispose();}if (DS != null && DS.Tables.Count > 0)return DS.Tables[0];elsereturn null;}/// <summary>/// 执行sql语句,返回受影响行数/// </summary>/// <param name="SqlStr"></param>/// <returns></returns>public int runSQLNoQuery(string SqlStr){int reint = 0;string connstr = Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = SqlStr;cm.CommandType = CommandType.Text;cm.CommandTimeout = 60;try{reint = cm.ExecuteNonQuery();}catch (Exception ex){WriteBarcodesLog(string.Format("执行sql时发生异常[{0}]:{1}", SqlStr, ex.Message), "runSQLNoQuery");}finally{cm.Connection.Close();cm.Dispose();}return reint;}/// <summary>/// 执行sql语句,返回指定值/// </summary>/// <param name="SqlStr"></param>/// <returns></returns>public int runSQLScalar(string SqlStr){int reint = 0;string connstr = Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = SqlStr;cm.CommandType = CommandType.Text;try{reint = Convert.ToInt32(cm.ExecuteScalar());}catch (Exception ex){WriteBarcodesLog(string.Format("执行sql时发生异常[{0}]:{1}", SqlStr, ex.Message));}finally{cm.Connection.Close();cm.Dispose();}return reint;}/// <summary>/// 运行存储过程,返回DataSet/// </summary>/// <param name="StoredProcedureName"></param>/// <returns></returns>public static DataSet runProcedure(string ProcedureName, List<sp_param> sps){string connstr = WX_Card.CardDAL.Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = ProcedureName;if (sps != null && sps.Count > 0){foreach (var sp in sps){SqlParameter sparam = new SqlParameter(sp.param_name, sp.param_value);cm.Parameters.Add(sparam);}}cm.CommandType = CommandType.StoredProcedure;DataSet DS = null;try{SqlDataAdapter da = new SqlDataAdapter(cm);DS = new DataSet();da.Fill(DS);da.Dispose();}catch (Exception ex){throw ex;}finally{cm.Connection.Close();cm.Dispose();}return DS;}/// <summary>/// 运行存储过程,无参数/// </summary>/// <param name="StoredProcedureName"></param>/// <returns></returns>public static void runProcedure(string ProcedureName){string connstr = WX_Card.CardDAL.Properties.Settings.Default.lswxConnectionString;SqlCommand cm = new SqlCommand();cm.Connection = new SqlConnection(connstr);cm.Connection.Open();cm.CommandText = ProcedureName;cm.CommandType = CommandType.StoredProcedure;DataSet DS = null;try{SqlDataAdapter da = new SqlDataAdapter(cm);DS = new DataSet();da.Fill(DS);da.Dispose();}catch (Exception ex){throw ex;}finally{cm.Connection.Close();cm.Dispose();}}/// <summary>/// 大批量数据插入/// </summary>public static void InsertTable(DataTable dt, string tableName){string connstr = Properties.Settings.Default.lswxConnectionString;using (SqlConnection conn = new SqlConnection(connstr)){Stopwatch sw = new Stopwatch();SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);bulkCopy.DestinationTableName = tableName;bulkCopy.BatchSize = dt.Rows.Count;conn.Open();sw.Start();if (dt != null && dt.Rows.Count > 120)//条目数必须大于120才更新库存,防止库存查询失败,平台库存被清空{bulkCopy.WriteToServer(dt);sw.Stop();}conn.Close();}}/// <summary>/// 根据时间戳获取时间/// </summary>/// <param name="timestamp"></param>/// <returns></returns>public static DateTime gettime(long timestamp){if (timestamp.Equals(0)){return DateTime.Now;}var start = new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Utc);return start.AddSeconds(timestamp);}/// <summary>/// 从指定时间开始/// </summary>/// <param name="dt"></param>/// <returns></returns>public static long GetTime(){DateTime DateStart = new DateTime(1970, 1, 1, 8, 0, 0);return Convert.ToInt64((DateTime.Now - DateStart).TotalSeconds);}/// <summary>/// 实体类转换(只支持单个类转换,不支持List)/// </summary>/// <typeparam name="TIn"></typeparam>/// <typeparam name="TOut"></typeparam>/// <param name="tIn"></param>/// <returns></returns>public static TOut Trans<TIn, TOut>(TIn tIn){TOut tOut = Activator.CreateInstance<TOut>();foreach (var outfield in tOut.GetType().GetFields()){foreach (var infield in tIn.GetType().GetFields()){if (outfield.Name.Equals(infield.Name)){try{outfield.SetValue(tOut, infield.GetValue(tIn));}catch{}break;}}}foreach (var outProperty in tOut.GetType().GetProperties()){foreach (var inProperty in tIn.GetType().GetProperties()){if (outProperty.Name.Equals(inProperty.Name)){try{outProperty.SetValue(tOut, inProperty.GetValue(tIn, null), null);}catch{}break;}}}return tOut;}/// <summary>/// 大批量数据插入,/// </summary>public static void InsertBatchData(DataTable dt, string tableName){string connstr = WX_Card.CardDAL.Properties.Settings.Default.lswxConnectionString;using (SqlConnection conn = new SqlConnection(connstr)){Stopwatch sw = new Stopwatch();SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);bulkCopy.DestinationTableName = tableName;bulkCopy.BatchSize = dt.Rows.Count;conn.Open();sw.Start();if (dt != null && dt.Rows.Count > 120)//条目数必须大于120才更新库存,防止库存查询失败,平台库存被清空{bulkCopy.WriteToServer(dt);sw.Stop();runProcedure("proc_CompareInventory");}conn.Close();}}}/// <summary>/// 执行存储过程附带的参数对象/// </summary>public class sp_param{/// <summary>/// 参数名/// </summary>public string param_name { get; set; }/// <summary>/// 参数值/// </summary>public string param_value { get; set; }}
}

C# sqlhelper相关推荐

  1. 一步一步写自己的SqlHelper类库

    前言: 一开始不懂SqlHelper是什么,以为是新东西.第一遍大量的查资料,在csdn上找到很多人写好的SqlHelper类,发现每个人写的很像,但又都不一样,找了一个能用的上的,敲了一遍别人的代码 ...

  2. one pragmatical sqlhelper

    namespace ConsoleApplication2 {using System;using System.Collections.Generic;using System.Linq;using ...

  3. C# SQLiteHelper类似SqlHelper类实现存取Sqlite数据库

    这个类不是我实现的,原文在这里,我修改了原文中分析sql语句参数的方法,将方法名修改为AttachParameters,将其修饰符修改为private,并直接传递command到这个方法,直接绑定参数 ...

  4. SQLserver数据库操作帮助类SqlHelper

    1 SqlHelper源码 using System; using System.Data; using System.Xml; using System.Data.SqlClient; using ...

  5. 一步步写自己SqlHelper类库(五):Command对象

    1.Command对象基础 当我们使用Connection对象里面的方法打开数据库后,要查询自己所需的数据或对数据库的内容进行增删改时,Command对象就派上用场了! MSDN定义:建立与数据源的连 ...

  6. JAVA入门到精通-第73讲-学生管理系统5-dao.sqlhelper

    -Model2模式 如果数据模型会很多,怎么办? 处理业务逻辑的:Model层 后台又分为:处理业务逻辑和对数据库的操作DAO-data access object -决定,再抽象一层出来:数据模型: ...

  7. 利用SqlHelper.cs实现Web程序对数据库的增、删、改等操作

    利用SqlHelper.cs实现Web程序对数据库的增.删.改等操作 (2006-08-22 00:50:05) 转载▼ 分类:技术杂谈 在SqlHelper.cs中,封装了所有和SQL数据库相关的操 ...

  8. 轻轻的我走了,正如我轻轻的来…——ADO.NET核心类的灭度与SQLHelper的诞生——十八相送(下)...

    源代码:13033480群共享 ADO.NET的SqlServer.NET数据提供程序,核心的类有4个,而在这个订餐系统中,我们只使用了3个,SqlConnection.SqlCommand.SqlD ...

  9. SqlHelper++

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  10. java sqlhelper_java版sqlhelper(转)

    packageSql;import java.sql.*;import java.util.logging.*;/*** SQL 基本操作 * 通过它,可以很轻松的使用 JDBC 来操纵数据库*/ p ...

最新文章

  1. Go 分布式学习利器(16) -- go中可复用的package构建
  2. Linux入门——文件管理
  3. 仿Office的程序载入窗体
  4. https跳转到http session丢失问题
  5. CUDA TOOlkit Programming Guide K. Unified Memory Programming
  6. 微信小程序手机号快速填写及会员卡开卡组件开放
  7. POJ 2773 Happy 2006 【数论,容斥原理+二分】
  8. Selenium RC for Java 环境配置
  9. Linux下PS命令详解 (转)
  10. (转)人工智能的钟摆
  11. 异贝,通过移动互联网技术,为中小微实体企业联盟、线上链接、线上线下自定义营销方案推送。案例38
  12. junit4报测试类class not found
  13. 高新科技培育钻石,或掀时尚界新热潮
  14. cad老是弹出命令中发生异常_CAD为什么会异常退出?遇到CAD异常退出怎么办-百度经验...
  15. [Linux学习] 实战系列之网络管理
  16. 使用 openssl 进行 base64 编解码
  17. c语言输入身高输出标准体重,项目2:就拿胖子说事---(4)计算出标准体重,输出体重状态(正常/超重/超轻)...
  18. Android视频录制
  19. Gdrive 使用教程
  20. 压力测试概念及方法(TPS/并发量)

热门文章

  1. 用代码做一个浪漫的“3D照片墙”
  2. 数据通信与计算机网复习题,数据通信与计算机网络 复习题总.doc
  3. python曲线库_测井曲线储量python库lasio解读使用
  4. 测井曲线wis文件格式转换为ASCII文本格式小软件的开发(C与Python结合开发)
  5. picasa android 缓存,从android应用上传到picasa
  6. MongoDB同步原理解析
  7. wmv怎么转换成视频mp4
  8. app版windows95
  9. STM32蜂鸣器驱动程序
  10. Fedora 14 x64 试用手记