#region 下载时重构insert(数据带null处理)
public void DownDataInsert(DataTable _dt, string TableName,DBHelper dbhelper)
{
List<string> _List = new List<string>();
try
{
if (_dt == null)
{
throw new Exception("datatable不可为空!");
}
if (string.IsNullOrEmpty(TableName))
{
throw new Exception("表名不可为空!");
} for (int i = ; i < _dt.Rows.Count; i++)
{
string sqlstring = string.Empty;
string sqlString = "insert into " + TableName + " ({0}) VALUES ({1})";
string Names = string.Empty;
string values = string.Empty;
foreach (DataColumn c in _dt.Columns)
{
if (_dt.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(_dt.Rows[i][c.ColumnName].ToString()))
{
Names += (string.IsNullOrEmpty(Names) ? "" : ",") + c.ColumnName;
if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
IsType(c.DataType, "System.Nullable`1[System.Double]") ||
IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
c.DataType == typeof(System.Int16) ||
c.DataType == typeof(System.Int32) ||
c.DataType == typeof(System.Int64) ||
c.DataType == typeof(System.Double) ||
c.DataType == typeof(System.Decimal))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + _dt.Rows[i][c.ColumnName].ToString();
} if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
c.DataType == typeof(System.DateTime))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + "DateTime('" + _dt.Rows[i][c.ColumnName].ToString() + "')";
}
if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + "'" + _dt.Rows[i][c.ColumnName].ToString() + "'";
}
}
}
if (!string.IsNullOrEmpty(Names) && !string.IsNullOrEmpty(values))
{
sqlstring = string.Format(sqlString, Names, values);
_List.Add(sqlstring);
}
}
dbhelper.ExecuteSqlTran(_List);
}
catch (Exception ex)
{
throw ex;
}
finally
{
_List = null;
}
}
#endregion #region 比较两个datatable,值不一样的相应的修改下载处理
public void CompareToDataTable(DataTable SourTable, DataTable TargetTable, string TableName)
{
string SelectString = string.Empty;
List<string> _list = new List<string>();
DataTable dtInsert = null;
DataTable drUpdate = null;
try
{
dtInsert = SourTable.Clone();
drUpdate = SourTable.Clone();
foreach (DataRow dr in SourTable.Rows)
{
if (TableName == "t_sellworker")
{
SelectString = "serverpartcode='" + dr["serverpartcode"].ToString() + "' and sellworkercode='" + dr["sellworkercode"].ToString() + "'";
}
else if (TableName == "t_salespromote")
{
SelectString = "salespromote_id=" + dr["salespromote_id"].ToString() + "";
// SelectString = "salespromote_startdate='" + dr["salespromote_startdate"].ToString() + "' and salespromote_enddate='" + dr["salespromote_enddate"].ToString() + "' " +
// " and salespromote_type='" + dr["salespromote_type"].ToString() + "' and salespromote_name='" + dr["salespromote_name"].ToString() + "' and commodity_code='" + dr["commodity_code"].ToString() + "'";
}
else if (TableName == "t_commodityex")
{
SelectString = "commodity_code='" + dr["commodity_code"].ToString() + "' and commodity_barcode='" + dr["commodity_barcode"].ToString() + "' "; // and serverpartshop_id=" + dr["serverpartshop_id"].ToString() + "
}
DataRow[] dr2 = TargetTable.Select(SelectString);
if (dr2 != null && dr2.Length > )
{
bool flag = false;
foreach (DataRow dr3 in dr2)
{
foreach (DataColumn c in SourTable.Columns)
{
if (dr3[c.ColumnName] != null && dr[c.ColumnName] != null && dr3[c.ColumnName].ToString() != dr[c.ColumnName].ToString())
{
flag = true;
break;
}
}
}
if (flag)
{
drUpdate.Rows.Add(dr.ItemArray);
}
}
else
{
dtInsert.Rows.Add(dr.ItemArray); //添加数据行
}
} if (drUpdate != null && drUpdate.Rows.Count > )
{
if(TableName=="t_sellworker")
{
UpdateData(drUpdate, "t_sellworker", new string[] { "serverpartcode", "sellworkercode" }, TargetDb);
}
else if (TableName == "t_salespromote")
{
UpdateData(drUpdate, "t_salespromote", new string[] { "salespromote_startdate", "salespromote_enddate", "salespromote_type", "salespromote_name", "commodity_code"}, TargetDb);
}
else if (TableName == "t_commodityex")
{
UpdateData(drUpdate, "t_commodityex", new string[] { "serverpartcode", "commodity_barcode", "serverpartshop_id" }, TargetDb);
}
MessageBox.Show("更新成功!");
}
if (dtInsert != null && dtInsert.Rows.Count > )
{
DownDataInsert(dtInsert, TableName, TargetDb);//插入
MessageBox.Show("下载成功!");
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dtInsert = null;
drUpdate = null;
}
}
#endregion #region 下载时重构update语句(处理数据空的情况)
public void UpdateData(DataTable table, string TableName, string[] keys,DBHelper dbhelper)
{
List<string> _List = null;
Dictionary<string, string> keyList = null;
try
{
if (_List == null)
{
_List = new List<string>();
}
else
{
_List.Clear();
} if (table == null)
{
throw new Exception("行不可为空!");
}
if (string.IsNullOrEmpty(TableName))
{
throw new Exception("表名不可为空!");
}
for (int i = ; i < table.Rows.Count; i++)
{
if (keyList == null)
{
keyList = new Dictionary<string, string>();
}
else
{
keyList.Clear();
}
string sqlstring = string.Empty;
string sqlString = "Update " + TableName + " set {0} where {1}";
string values = string.Empty;
foreach (DataColumn c in table.Columns)
{
if (table.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(table.Rows[i][c.ColumnName].ToString()))
{
if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
IsType(c.DataType, "System.Nullable`1[System.Double]") ||
IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
c.DataType == typeof(System.Int16) ||
c.DataType == typeof(System.Int32) ||
c.DataType == typeof(System.Int64) ||
c.DataType == typeof(System.Double) ||
c.DataType == typeof(System.Decimal))
{
values += ((string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + table.Rows[i][c.ColumnName].ToString());
if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
{
keyList.Add(c.ColumnName, table.Rows[i][c.ColumnName].ToString());
}
} if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
c.DataType == typeof(System.DateTime))
{
values += ((string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + "DateTime('" + table.Rows[i][c.ColumnName].ToString() + "')");
if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
{
keyList.Add(c.ColumnName, "DateTime('" + table.Rows[i][c.ColumnName].ToString() + "')");
}
}
if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + c.ColumnName + "=" + "'" + table.Rows[i][c.ColumnName].ToString() + "'";
if (keys.Contains(c.ColumnName.ToUpper()) || keys.Contains(c.ColumnName.ToLower()))
{
keyList.Add(c.ColumnName, "'" + table.Rows[i][c.ColumnName].ToString() + "'");
}
}
}
}
if (!string.IsNullOrEmpty(values) && keyList != null && keyList.Count == keys.Length)
{
string strKeys = string.Empty;
foreach (KeyValuePair<string, string> kvp in keyList)
{
strKeys += ((string.IsNullOrEmpty(strKeys) ? "" : " AND ") + kvp.Key + " = " + kvp.Value);
} if (!string.IsNullOrEmpty(strKeys))
{
sqlstring = string.Format(sqlString, values, strKeys);
_List.Add(sqlstring);
} }
}
dbhelper.ExecuteSqlTran(_List);
}
catch (Exception ex)
{
throw ex;
}
finally
{
_List = null;
keyList = null;
}
}
#endregion
#region 上传时重构目标数据表insert(数据中带null的处理)
public void InsertTableData(DataTable dt, string TableName, DBHelper dbhelper)
{
try
{
List<string> _List = new List<string>();
if (dt == null)
{
throw new Exception("datatable不可为空!");
}
if (string.IsNullOrEmpty(TableName))
{
throw new Exception("表名不可为空!");
} for (int i = ; i < dt.Rows.Count; i++)
{
string sqlstring = string.Empty;
string sqlString = "insert into " + TableName + " ({0}) VALUES ({1})";
string Names = string.Empty;
string values = string.Empty;
foreach (DataColumn c in dt.Columns)
{
if (dt.Rows[i][c.ColumnName] != null && !string.IsNullOrEmpty(dt.Rows[i][c.ColumnName].ToString()))
{
Names += (string.IsNullOrEmpty(Names) ? "" : ",") + c.ColumnName;
if (IsType(c.DataType, "System.Nullable`1[System.Int16]") ||
IsType(c.DataType, "System.Nullable`1[System.Int32]") ||
IsType(c.DataType, "System.Nullable`1[System.Int64]") ||
IsType(c.DataType, "System.Nullable`1[System.Double]") ||
IsType(c.DataType, "System.Nullable`1[System.Decimal]") ||
c.DataType == typeof(System.Int16) ||
c.DataType == typeof(System.Int32) ||
c.DataType == typeof(System.Int64) ||
c.DataType == typeof(System.Double) ||
c.DataType == typeof(System.Decimal))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + dt.Rows[i][c.ColumnName].ToString();
} if (IsType(c.DataType, "System.Nullable`1[System.DateTime]") ||
c.DataType == typeof(System.DateTime))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + "DateTime('" + dt.Rows[i][c.ColumnName].ToString() + "')";
}
if (IsType(c.DataType, "System.String") || c.DataType == typeof(System.String))
{
values += (string.IsNullOrEmpty(values) ? "" : ",") + "'" + dt.Rows[i][c.ColumnName].ToString() + "'";
}
}
}
if (!string.IsNullOrEmpty(Names) && !string.IsNullOrEmpty(values))
{
sqlstring = string.Format(sqlString, Names, values);
_List.Add(sqlstring);
}
}
dbhelper.ExecuteSqlTran(_List);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
 DBHelper SourceDb = new DBHelper("192.168.11.197", "pos1101", "dba", "sql");//源数据库
DBHelper TargetDb = new DBHelper("127.0.0.1", "pos012", "dba", "sql"); //目标
public class DBHelper
{
#region 构造函数
public DBHelper(string ConnStr)
{
connstring = ConnStr;
} public DBHelper(string Host, string Server, string UserId, string Password)
{
connstring = "host=" + Host + ";server=" + Server + ";userid=" + UserId + ";password=" + Password + ";";
} public DBHelper()
{ }
#endregion #region 属性信息
private string connstring = null;
public string ConnStr
{
set
{
connstring = value;
}
get
{
return connstring;
}
}
#endregion public DataSet QueryOdbc(string SqlString)
{
using (SAConnection conn = new SAConnection(connstring))
{
SACommand cmd = new SACommand(SqlString, conn);
try
{
conn.Open();
SADataAdapter adp = new SADataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
conn.Close();
return ds;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
} /// <summary>
/// 保存数据
/// </summary>
/// <param name="SQLStringList"></param>
public void ExecuteSqlTran(List<string> SQLStringList)
{
using (SAConnection conn = new SAConnection(connstring))
{
conn.Open();
SACommand cmd = new SACommand
{
Connection = conn
};
SATransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int i = ; i < SQLStringList.Count; i++)
{
string strsql = SQLStringList[i].ToString();
if (strsql.Trim().Length > )
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
}
} /// <summary>
/// 保存数据
/// </summary>
/// <param name="SQLStringList"></param>
public void ExecuteSqlTran(string SQLString)
{
using (SAConnection conn = new SAConnection(connstring))
{
conn.Open();
SACommand cmd = new SACommand
{
Connection = conn
};
SATransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
if (SQLString.Trim().Length > )
{
cmd.CommandText = SQLString;
cmd.ExecuteNonQuery();
}
tx.Commit();
}
catch (Exception E)
{
tx.Rollback();
throw new Exception(E.Message);
}
finally
{
conn.Close();
}
}
} /// <summary>
/// 获取最大主键ID
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public int OdbcGetMaxPKID(string SqlString)
{
using (SAConnection conn = new SAConnection(connstring))
{
SACommand cmd = new SACommand(SqlString, conn);
try
{
conn.Open();
int max_id = cmd.ExecuteScalar().ToString().Equals("") ? : int.Parse(cmd.ExecuteScalar().ToString());
conn.Close();
return max_id;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
} ///// <summary>
///// 测试连接
///// </summary>
//public static void TestConn()
//{
// using (SAConnection Conn = new SAConnection(connstring))
// {
// Conn.Open();
// SACommand cmd = new SACommand();
// cmd.Connection = Conn;
// Conn.Close();
// }
//}
}

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. [BZOJ2821]作诗(分块)

    题意 N个数,M组询问,每次问[l,r]中有多少个数出现正偶数次对于100%的数据,1≤n,c,m≤105 题解 (传说lyd省选的时候看错题   把题看成这个了   从此又多了一道分块神题)把N个数 ...

  2. 单调队列&单调栈归纳

    单调队列 求长度为M的区间内的最大(小)值 单调队列的基本操作,也就是经典的滑动窗口问题. 求长度为M的区间内最大值和最小值的最大差值 两个单调队列,求出长度为M的区间最大最小值的数组,分别求最大最小 ...

  3. 洛谷—— P1877 [HAOI2012]音量调节

    https://www.luogu.org/problem/show?pid=1877#sub 题目描述 一个吉他手准备参加一场演出.他不喜欢在演出时始终使用同一个音量,所以他决定每一首歌之前他都需要 ...

  4. 国庆 day 6 上午

    1. 角谷猜想(kakutani.pas/c/cpp)(kakutani.in/out)时间限制:1s/空间限制:256M[题目描述] 某个名字末尾是 654321 的小 A 同学是个大家眼中公认的学 ...

  5. C++函数指针相关 & 类成员的指针 & 成员函数的指针

    有时候会有指向类成员变量或者成员函数的指针,但是注意,这个指针并不是针对一个地址的指向,而更多的是一个偏移. 同时,支持将父类对象的成员 转为 子类对象的成员指针,如下: 反过来,是不行的.因为父类的 ...

  6. 从串口设置、读取、并分析um220模块的数据

    转载请注明:http://blog.csdn.net/wang_zheng_kai 导航制导与控制实验室 2014年11月10日 好久没有写博客了,先从一个小小的程序開始一段新的历程吧. 近期的项目主 ...

  7. 如何保证对象线程内唯一:数据槽(CallContext)

    CallContext 是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽.数据槽不在其他逻辑线程上的调用上下文之间共享.当 CallContext 沿执行代码路径 ...

  8. 基于Linux下Iptables限制BT下载的研究

    基于Linux下Iptables限制BT下载的研究   摘要:     当前BT下载技术和软件飞速发展,给人们网上冲浪获取资源带来了极大的便利, 但同时BT占用大量的网络带宽等资源也给网络和网络管理员 ...

  9. noip 2018 day2 T1 旅行 基环树 tarjan

    Code: #include<cstdio> #include<cstring> #include<string> #include<stack> #i ...

  10. 计算机科学书籍推荐和CSS、js书籍推荐

    计算机科学:<深入理解计算机系统>,这是基础知识 JavaScript:JavaScript高级程序设计:大名鼎鼎的红宝书 <精通CSS:高级Web标准解决方案>:因为我觉CS ...