1. #region 下载时重构insert(数据带null处理)
  2. public void DownDataInsert(DataTable _dt, string TableName,DBHelper dbhelper)
  3. {
  4. List<string> _List = new List<string>();
  5. try
  6. {
  7. if (_dt == null)
  8. {
  9. throw new Exception("datatable不可为空!");
  10. }
  11. if (string.IsNullOrEmpty(TableName))
  12. {
  13. throw new Exception("表名不可为空!");
  14. }
  15.  
  16. for (int i = ; i < _dt.Rows.Count; i++)
  17. {
  18. string sqlstring = string.Empty;
  19. string sqlString = "insert into " + TableName + " ({0}) VALUES ({1})";
  20. string Names = string.Empty;
  21. string values = string.Empty;
  22. foreach (DataColumn c in _dt.Columns)
  23. {
  24. if (_dt.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(_dt.Rows[i][c.ColumnName].ToString()))
  25. {
  26. Names += (string.IsNullOrEmpty(Names) ? "" : ",") + c.ColumnName;
  27. if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
  28. IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
  29. IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
  30. IsType(c.DataType, "System.Nullable`1[System.Double]") ||
  31. IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
  32. c.DataType == typeof(System.Int16) ||
  33. c.DataType == typeof(System.Int32) ||
  34. c.DataType == typeof(System.Int64) ||
  35. c.DataType == typeof(System.Double) ||
  36. c.DataType == typeof(System.Decimal))
  37. {
  38. values += (string.IsNullOrEmpty(values) ? "" : ",") + _dt.Rows[i][c.ColumnName].ToString();
  39. }
  40.  
  41. if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
  42. c.DataType == typeof(System.DateTime))
  43. {
  44. values += (string.IsNullOrEmpty(values) ? "" : ",") + "DateTime('" + _dt.Rows[i][c.ColumnName].ToString() + "')";
  45. }
  46. if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
  47. {
  48. values += (string.IsNullOrEmpty(values) ? "" : ",") + "'" + _dt.Rows[i][c.ColumnName].ToString() + "'";
  49. }
  50. }
  51. }
  52. if (!string.IsNullOrEmpty(Names) && !string.IsNullOrEmpty(values))
  53. {
  54. sqlstring = string.Format(sqlString, Names, values);
  55. _List.Add(sqlstring);
  56. }
  57. }
  58. dbhelper.ExecuteSqlTran(_List);
  59. }
  60. catch (Exception ex)
  61. {
  62. throw ex;
  63. }
  64. finally
  65. {
  66. _List = null;
  67. }
  68. }
  69. #endregion
  70.  
  71. #region 比较两个datatable,值不一样的相应的修改下载处理
  72. public void CompareToDataTable(DataTable SourTable, DataTable TargetTable, string TableName)
  73. {
  74. string SelectString = string.Empty;
  75. List<string> _list = new List<string>();
  76. DataTable dtInsert = null;
  77. DataTable drUpdate = null;
  78. try
  79. {
  80. dtInsert = SourTable.Clone();
  81. drUpdate = SourTable.Clone();
  82. foreach (DataRow dr in SourTable.Rows)
  83. {
  84. if (TableName == "t_sellworker")
  85. {
  86. SelectString = "serverpartcode='" + dr["serverpartcode"].ToString() + "' and sellworkercode='" + dr["sellworkercode"].ToString() + "'";
  87. }
  88. else if (TableName == "t_salespromote")
  89. {
  90. SelectString = "salespromote_id=" + dr["salespromote_id"].ToString() + "";
  91. // SelectString = "salespromote_startdate='" + dr["salespromote_startdate"].ToString() + "' and salespromote_enddate='" + dr["salespromote_enddate"].ToString() + "' " +
  92. // " and salespromote_type='" + dr["salespromote_type"].ToString() + "' and salespromote_name='" + dr["salespromote_name"].ToString() + "' and commodity_code='" + dr["commodity_code"].ToString() + "'";
  93. }
  94. else if (TableName == "t_commodityex")
  95. {
  96. SelectString = "commodity_code='" + dr["commodity_code"].ToString() + "' and commodity_barcode='" + dr["commodity_barcode"].ToString() + "' "; // and serverpartshop_id=" + dr["serverpartshop_id"].ToString() + "
  97. }
  98. DataRow[] dr2 = TargetTable.Select(SelectString);
  99. if (dr2 != null && dr2.Length > )
  100. {
  101. bool flag = false;
  102. foreach (DataRow dr3 in dr2)
  103. {
  104. foreach (DataColumn c in SourTable.Columns)
  105. {
  106. if (dr3[c.ColumnName] != null && dr[c.ColumnName] != null && dr3[c.ColumnName].ToString() != dr[c.ColumnName].ToString())
  107. {
  108. flag = true;
  109. break;
  110. }
  111. }
  112. }
  113. if (flag)
  114. {
  115. drUpdate.Rows.Add(dr.ItemArray);
  116. }
  117. }
  118. else
  119. {
  120. dtInsert.Rows.Add(dr.ItemArray); //添加数据行
  121. }
  122. }
  123.  
  124. if (drUpdate != null && drUpdate.Rows.Count > )
  125. {
  126. if(TableName=="t_sellworker")
  127. {
  128. UpdateData(drUpdate, "t_sellworker", new string[] { "serverpartcode", "sellworkercode" }, TargetDb);
  129. }
  130. else if (TableName == "t_salespromote")
  131. {
  132. UpdateData(drUpdate, "t_salespromote", new string[] { "salespromote_startdate", "salespromote_enddate", "salespromote_type", "salespromote_name", "commodity_code"}, TargetDb);
  133. }
  134. else if (TableName == "t_commodityex")
  135. {
  136. UpdateData(drUpdate, "t_commodityex", new string[] { "serverpartcode", "commodity_barcode", "serverpartshop_id" }, TargetDb);
  137. }
  138. MessageBox.Show("更新成功!");
  139. }
  140. if (dtInsert != null && dtInsert.Rows.Count > )
  141. {
  142. DownDataInsert(dtInsert, TableName, TargetDb);//插入
  143. MessageBox.Show("下载成功!");
  144. }
  145.  
  146. }
  147. catch (Exception ex)
  148. {
  149. MessageBox.Show(ex.Message);
  150. }
  151. finally
  152. {
  153. dtInsert = null;
  154. drUpdate = null;
  155. }
  156. }
  157. #endregion
  158.  
  159. #region 下载时重构update语句(处理数据空的情况)
  160. public void UpdateData(DataTable table, string TableName, string[] keys,DBHelper dbhelper)
  161. {
  162. List<string> _List = null;
  163. Dictionary<string, string> keyList = null;
  164. try
  165. {
  166. if (_List == null)
  167. {
  168. _List = new List<string>();
  169. }
  170. else
  171. {
  172. _List.Clear();
  173. }
  174.  
  175. if (table == null)
  176. {
  177. throw new Exception("行不可为空!");
  178. }
  179. if (string.IsNullOrEmpty(TableName))
  180. {
  181. throw new Exception("表名不可为空!");
  182. }
  183. for (int i = ; i < table.Rows.Count; i++)
  184. {
  185. if (keyList == null)
  186. {
  187. keyList = new Dictionary<string, string>();
  188. }
  189. else
  190. {
  191. keyList.Clear();
  192. }
  193. string sqlstring = string.Empty;
  194. string sqlString = "Update " + TableName + " set {0} where {1}";
  195. string values = string.Empty;
  196. foreach (DataColumn c in table.Columns)
  197. {
  198. if (table.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(table.Rows[i][c.ColumnName].ToString()))
  199. {
  200. if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
  201. IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
  202. IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
  203. IsType(c.DataType, "System.Nullable`1[System.Double]") ||
  204. IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
  205. c.DataType == typeof(System.Int16) ||
  206. c.DataType == typeof(System.Int32) ||
  207. c.DataType == typeof(System.Int64) ||
  208. c.DataType == typeof(System.Double) ||
  209. c.DataType == typeof(System.Decimal))
  210. {
  211. values += ((string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + table.Rows[i][c.ColumnName].ToString());
  212. if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
  213. {
  214. keyList.Add(c.ColumnName, table.Rows[i][c.ColumnName].ToString());
  215. }
  216. }
  217.  
  218. if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
  219. c.DataType == typeof(System.DateTime))
  220. {
  221. values += ((string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + "DateTime('" + table.Rows[i][c.ColumnName].ToString() + "')");
  222. if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
  223. {
  224. keyList.Add(c.ColumnName, "DateTime('" + table.Rows[i][c.ColumnName].ToString() + "')");
  225. }
  226. }
  227. if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
  228. {
  229. values += (string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + "'" + table.Rows[i][c.ColumnName].ToString() + "'";
  230. if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
  231. {
  232. keyList.Add(c.ColumnName, "'" + table.Rows[i][c.ColumnName].ToString() + "'");
  233. }
  234. }
  235. }
  236. }
  237. if (!string.IsNullOrEmpty(values) && keyList != null && keyList.Count == keys.Length)
  238. {
  239. string strKeys = string.Empty;
  240. foreach (KeyValuePair<string, string> kvp in keyList)
  241. {
  242. strKeys += ((string.IsNullOrEmpty(strKeys) ? "" : " AND ") + kvp.Key + " = " + kvp.Value);
  243. }
  244.  
  245. if (!string.IsNullOrEmpty(strKeys))
  246. {
  247. sqlstring = string.Format(sqlString, values, strKeys);
  248. _List.Add(sqlstring);
  249. }
  250.  
  251. }
  252. }
  253. dbhelper.ExecuteSqlTran(_List);
  254. }
  255. catch (Exception ex)
  256. {
  257. throw ex;
  258. }
  259. finally
  260. {
  261. _List = null;
  262. keyList = null;
  263. }
  264. }
  265. #endregion
  266. #region 上传时重构目标数据表insert(数据中带null的处理)
  267. public void InsertTableData(DataTable dt, string TableName, DBHelper dbhelper)
  268. {
  269. try
  270. {
  271. List<string> _List = new List<string>();
  272. if (dt == null)
  273. {
  274. throw new Exception("datatable不可为空!");
  275. }
  276. if (string.IsNullOrEmpty(TableName))
  277. {
  278. throw new Exception("表名不可为空!");
  279. }
  280.  
  281. for (int i = ; i < dt.Rows.Count; i++)
  282. {
  283. string sqlstring = string.Empty;
  284. string sqlString = "insert into " + TableName + " ({0}) VALUES ({1})";
  285. string Names = string.Empty;
  286. string values = string.Empty;
  287. foreach (DataColumn c in dt.Columns)
  288. {
  289. if (dt.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(dt.Rows[i][c.ColumnName].ToString()))
  290. {
  291. Names += (string.IsNullOrEmpty(Names) ? "" : ",") + c.ColumnName;
  292. if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
  293. IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
  294. IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
  295. IsType(c.DataType, "System.Nullable`1[System.Double]") ||
  296. IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
  297. c.DataType == typeof(System.Int16) ||
  298. c.DataType == typeof(System.Int32) ||
  299. c.DataType == typeof(System.Int64) ||
  300. c.DataType == typeof(System.Double) ||
  301. c.DataType == typeof(System.Decimal))
  302. {
  303. values += (string.IsNullOrEmpty(values) ? "" : ",") + dt.Rows[i][c.ColumnName].ToString();
  304. }
  305.  
  306. if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
  307. c.DataType == typeof(System.DateTime))
  308. {
  309. values += (string.IsNullOrEmpty(values) ? "" : ",") + "DateTime('" + dt.Rows[i][c.ColumnName].ToString() + "')";
  310. }
  311. if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
  312. {
  313. values += (string.IsNullOrEmpty(values) ? "" : ",") + "'" + dt.Rows[i][c.ColumnName].ToString() + "'";
  314. }
  315. }
  316. }
  317. if (!string.IsNullOrEmpty(Names) && !string.IsNullOrEmpty(values))
  318. {
  319. sqlstring = string.Format(sqlString, Names, values);
  320. _List.Add(sqlstring);
  321. }
  322. }
  323. dbhelper.ExecuteSqlTran(_List);
  324. }
  325. catch (Exception ex)
  326. {
  327. throw ex;
  328. }
  329. }
  330. #endregion
  1. DBHelper SourceDb = new DBHelper("192.168.11.197", "pos1101", "dba", "sql");//源数据库
  2. DBHelper TargetDb = new DBHelper("127.0.0.1", "pos012", "dba", "sql"); //目标
  1. public class DBHelper
  2. {
  3. #region 构造函数
  4. public DBHelper(string ConnStr)
  5. {
  6. connstring = ConnStr;
  7. }
  8.  
  9. public DBHelper(string Host, string Server, string UserId, string Password)
  10. {
  11. connstring = "host=" + Host + ";server=" + Server + ";userid=" + UserId + ";password=" + Password + ";";
  12. }
  13.  
  14. public DBHelper()
  15. {
  16.  
  17. }
  18. #endregion
  19.  
  20. #region 属性信息
  21. private string connstring = null;
  22. public string ConnStr
  23. {
  24. set
  25. {
  26. connstring = value;
  27. }
  28. get
  29. {
  30. return connstring;
  31. }
  32. }
  33. #endregion
  34.  
  35. public DataSet QueryOdbc(string SqlString)
  36. {
  37. using (SAConnection conn = new SAConnection(connstring))
  38. {
  39. SACommand cmd = new SACommand(SqlString, conn);
  40. try
  41. {
  42. conn.Open();
  43. SADataAdapter adp = new SADataAdapter(cmd);
  44. DataSet ds = new DataSet();
  45. adp.Fill(ds);
  46. conn.Close();
  47. return ds;
  48. }
  49. catch (Exception ex)
  50. {
  51. throw new Exception(ex.Message);
  52. }
  53. }
  54. }
  55.  
  56. /// <summary>
  57. /// 保存数据
  58. /// </summary>
  59. /// <param name="SQLStringList"></param>
  60. public void ExecuteSqlTran(List<string> SQLStringList)
  61. {
  62. using (SAConnection conn = new SAConnection(connstring))
  63. {
  64. conn.Open();
  65. SACommand cmd = new SACommand
  66. {
  67. Connection = conn
  68. };
  69. SATransaction tx = conn.BeginTransaction();
  70. cmd.Transaction = tx;
  71. try
  72. {
  73. for (int i = ; i < SQLStringList.Count; i++)
  74. {
  75. string strsql = SQLStringList[i].ToString();
  76. if (strsql.Trim().Length > )
  77. {
  78. cmd.CommandText = strsql;
  79. cmd.ExecuteNonQuery();
  80. }
  81. }
  82. tx.Commit();
  83. }
  84. catch (Exception ex)
  85. {
  86. tx.Rollback();
  87. throw new Exception(ex.Message);
  88. }
  89. finally
  90. {
  91. conn.Close();
  92. }
  93. }
  94. }
  95.  
  96. /// <summary>
  97. /// 保存数据
  98. /// </summary>
  99. /// <param name="SQLStringList"></param>
  100. public void ExecuteSqlTran(string SQLString)
  101. {
  102. using (SAConnection conn = new SAConnection(connstring))
  103. {
  104. conn.Open();
  105. SACommand cmd = new SACommand
  106. {
  107. Connection = conn
  108. };
  109. SATransaction tx = conn.BeginTransaction();
  110. cmd.Transaction = tx;
  111. try
  112. {
  113. if (SQLString.Trim().Length > )
  114. {
  115. cmd.CommandText = SQLString;
  116. cmd.ExecuteNonQuery();
  117. }
  118. tx.Commit();
  119. }
  120. catch (Exception E)
  121. {
  122. tx.Rollback();
  123. throw new Exception(E.Message);
  124. }
  125. finally
  126. {
  127. conn.Close();
  128. }
  129. }
  130. }
  131.  
  132. /// <summary>
  133. /// 获取最大主键ID
  134. /// </summary>
  135. /// <param name="SqlString"></param>
  136. /// <returns></returns>
  137. public int OdbcGetMaxPKID(string SqlString)
  138. {
  139. using (SAConnection conn = new SAConnection(connstring))
  140. {
  141. SACommand cmd = new SACommand(SqlString, conn);
  142. try
  143. {
  144. conn.Open();
  145. int max_id = cmd.ExecuteScalar().ToString().Equals("") ? : int.Parse(cmd.ExecuteScalar().ToString());
  146. conn.Close();
  147. return max_id;
  148. }
  149. catch (Exception ex)
  150. {
  151. throw new Exception(ex.Message);
  152. }
  153. }
  154. }
  155.  
  156. ///// <summary>
  157. ///// 测试连接
  158. ///// </summary>
  159. //public static void TestConn()
  160. //{
  161. // using (SAConnection Conn = new SAConnection(connstring))
  162. // {
  163. // Conn.Open();
  164. // SACommand cmd = new SACommand();
  165. // cmd.Connection = Conn;
  166. // Conn.Close();
  167. // }
  168. //}
  169. }

dbhelper类

重构insert update 比较两个datatbale的更多相关文章

  1. PHP5: mysqli 插入, 查询, 更新和删除 Insert Update Delete Using mysqli (CRUD)

    原文: PHP5: mysqli 插入, 查询, 更新和删除  Insert Update Delete Using mysqli (CRUD) PHP 5 及以上版本建议使用以下方式连接 MySQL ...

  2. 《oracle每天一练》Merge Into 语句代替Insert/Update在Oracle中的应用实战

    转载自窃破天道 动机: 想在Oracle中用一条SQL语句直接进行Insert/Update的操作. 说明: 在进行SQL语句编写时,我们经常会遇到大量的同时进行Insert/Update的语句 ,也 ...

  3. 使用Merge Into 语句实现 Insert/Update

    网址: http://www.eygle.com/digest/2009/01/merge_into_insertupdate.html 动机: 想在Oracle中用一条SQL语句直接进行Insert ...

  4. Merge Into 语句代替Insert/Update在Oracle中的应用实战

    动机: 想在Oracle中用一条SQL语句直接进行Insert/Update的操作. 说明: 在进行SQL语句编写时,我们经常会遇到大量的同时进行Insert/Update的语句 ,也就是说当存在记录 ...

  5. Oracle Merge Into Insert/Update

    出自:http://blog.csdn.net/yuzhic/article/details/1896878 动机: 想在Oracle中用一条SQL语句直接进行Insert/Update的操作. 说明 ...

  6. mysql数据恢复 insert\update\delete 工具MyFlash

    一.简介MyFlash是由美团点评公司技术工程部开发维护的一个回滚DML操作的工具.该工具通过解析v4版本的binlog,完成回滚操作.相对已有的回滚工具,其增加了更多的过滤选项,让回滚更加容易. 该 ...

  7. LINQ体验(9)——LINQ to SQL语句之Insert/Update/Delete操作

    我们继续讲解LINQ to SQL语句,这篇我们来讨论Insert/Update/Delete操作.这个在我们的程序中最为常用了.我们直接看例子. Insert/Update/Delete操作 插入( ...

  8. 关于MyBatis mapper的insert, update, delete返回值

    这里做了比较清晰的解释: http://mybatis.github.io/mybatis-3/java-api.html SqlSession As mentioned above, the Sql ...

  9. mysql 事务是专门用来管理insert,update,delete语句的,和select语句一点不相干

    1.mysql 事务是专门用来管理insert,update,delete语句的,和select语句一点不相干 2.一般来说,事务是必须满足4个条件(ACID): Atomicity(原子性).Con ...

随机推荐

  1. 结合Vue 的滚动底部加载

    项目手机端分页跳转不理想,自己做了一个滚动加载的一个Demo 核心Dom结构 <body> <div id="Content"> <div> & ...

  2. linux学习之高并发服务器篇(二)

    高并发服务器 1.线程池并发服务器 两种模型: 预先创建阻塞于accept多线程,使用互斥锁上锁保护accept(减少了每次创建线程的开销) 预先创建多线程,由主线程调用accept 线程池 3.多路 ...

  3. CSU 1249 竞争性酶抑制剂和同工酶

    1249: 竞争性酶抑制剂和同工酶 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 109  Solved: 49 Description 人体内很多化学 ...

  4. bootstrap结合google code prettify的问题

    发现prettify不能显示行号,于是上网找了解决方法: 只使用prettify的js的文件,不使用css文件,另外添加这段css: .com { color: #93a1a1; } .lit { c ...

  5. KVM硬件辅助虚拟化之 EPT in Nested Virtualization

    在嵌套虚拟环境(Nested Virtualization)下,执行在hypervisor上的Virtual Machine仍能够作为hypervisor去执行其他的Virutal Machine,而 ...

  6. 利用opencv源代码和vs编程序训练分类器haartraining.cpp

    如需转载请注明本博网址:http://blog.csdn.net/ding977921830/article/details/47733363. 一  训练框架 训练人脸检測分类器须要三个步骤: (1 ...

  7. 负载均衡-lvs

    常用的负载均衡技术比较DNS 轮询DNS本身的机制不再赘述,这里主要看一看基于DNS的负载均衡,其大致原理很清楚,DNS系统本身支持同一个域名映射到多个ip (A记录),例如 这样每次向DNS系统询问 ...

  8. 963B:Destruction of a Tree

    You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any ve ...

  9. Coderfroces 864 E. Fire(01背包+路径标记)

    E. Fire http://codeforces.com/problemset/problem/864/E Polycarp is in really serious trouble — his h ...

  10. Assembly.Load 详解(c#)

    我们在使用C# 语言的Assembly.Load 来加载托管程序集并使用反射功能时,一般需要先通过Assembly.Load(), Assembly.LoadFrom() 等方法将目标托管程序集加载到 ...