using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MySql.Data.MySqlClient; namespace CNAS_DBSync { public class MySQLBaseDAL { private static log4net.ILog log = log4net.LogManager.GetLogger("MySQLBaseDAL"); public void CreateConnectString(string strIP,string strPort,string strName, string strUser, string strPwd) { MySQLHelper.InitConnectionString(strIP,strPort,strName,strUser,strPwd); } //获取所有表单名称 public DataTable GetTableNames(string strName) { DataTable dt = new DataTable(); string strSql = string.Format("SELECT table_name as TABNAME FROM information_schema.TABLES WHERE table_schema='{0}'", strName); try { dt = MySQLHelper.ExecuteDataSet(strSql).Tables[0]; } catch (Exception ex) { log.Error(ex.Message); } return dt; } /// /// 获取某表的表结构 /// /// /// public DataTable GetTableStruct(string strTableName) { DataTable dt = new DataTable(); string strSql = string.Format("SELECT * FROM {0} Where 1=0", strTableName); try { dt = MySQLHelper.ExecuteDataSet(strSql).Tables[0]; } catch (Exception ex) { log.Error(ex.Message); } return dt; } /// /// 获取某表的表结构和类型长度 /// /// /// public DataTable GetTableTypeAndLenth(string strTableName) { DataTable dt = new DataTable(); string strSql = string.Format("select COLUMN_NAME AS 'ColumnName',IS_NULLABLE AS 'IsNullable',DATA_TYPE AS 'DataType',CHARACTER_MAXIMUM_LENGTH AS 'CharMaxLenth',CHARACTER_OCTET_LENGTH AS 'CharOcterLenth',NUMERIC_PRECISION AS 'NumericPrecision',NUMERIC_SCALE AS 'NumericScale' FROM information_schema.COLUMNS WHERE TABLE_NAME LIKE '{0}'", strTableName); try { dt = MySQLHelper.ExecuteDataSet(strSql).Tables[0]; } catch (Exception ex) { log.Error(ex.Message); } return dt; } /// /// 逐行批量插入数据 /// /// /// public int InsertCnasData(DataTable dt, List syncParamasInfos) { int iReturn = 0; if (dt.Rows.Count <= 0) return 0; try { //构建SQL语句 string strSql_part1 = ""; string strSql_part2 = ""; foreach (var item in syncParamasInfos) { strSql_part1 += item.TargetField + ","; strSql_part2 += string.Format("@{0},",item.TargetField); } string strSql = string.Format("insert into {0}({1}) values({2})", syncParamasInfos[0].TargetTable, strSql_part1.Substring(0, strSql_part1.Length - 1), strSql_part2.Substring(0, strSql_part2.Length - 1)); foreach (DataRow dr in dt.Rows) { MySqlParameter[] parameters = new MySqlParameter[syncParamasInfos.Count]; for (int i = 0; i < syncParamasInfos.Count; i++) { parameters[i] = new MySqlParameter(syncParamasInfos[i].TargetField, dr[syncParamasInfos[i].TargetField]); } //执行SQL语句 iReturn += MySQLHelper.ExecuteNonQuery(strSql, parameters); } } catch (Exception ex) { //此处添加错误日志 log.Error(ex.Message); } return iReturn; } public bool LinkCnasTest() { return MySQLHelper.TestConnectMySql(); } } }