使用entitiy

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data;
  6 using System.Data.SqlClient;
  7
  8 namespace SQL
  9 {
 10     public class DBParse
 11     {
 12         /// <summary>
 13         /// 獲取DB中所有的表格
 14         /// </summary>
 15         /// <returns></returns>
 16         public List<TableEntity> GetAllTable()
 17         {
 18             string sql = "SELECT Name FROM SysObjects Where XType=‘U‘ ORDER BY Name";
 19             DataTable dt = DbHelperSQL.Query(sql).Tables[0];
 20             List<TableEntity> list = new List<TableEntity>();
 21             if (dt != null && dt.Rows.Count > 0)
 22             {
 23                 foreach (DataRow dr in dt.Rows)
 24                 {
 25                     TableEntity entity = new TableEntity() { TableName = dr["Name"].ToString() };
 26                     list.Add(entity);
 27                 }
 28             }
 29
 30             return list;
 31         }
 32
 33         public List<TableInfoEntity> GetTableInfo(string tablename)
 34         {
 35             string strProc = "sp_columns";
 36             SqlParameter[] parameters = {
 37                     new SqlParameter("@table_name", SqlDbType.VarChar,50)
 38                                         };
 39             parameters[0].Value = tablename;
 40             DataTable dt = DbHelperSQL.RunProcedure(strProc,parameters,tablename).Tables[0];
 41             List<TableInfoEntity> list = new List<TableInfoEntity>();
 42             List<TablePKEntity> list_PK = GetTablePK(tablename);
 43             string strPK = "";
 44             string strpk_name = "";
 45             foreach (TablePKEntity pk in list_PK)
 46             {
 47                 strPK += pk.PK_ColumnName + ",";
 48             }
 49             if (list_PK != null && list_PK.Count > 0)
 50             {
 51                 if (!string.IsNullOrWhiteSpace(list_PK[0].PK_Name))
 52                 {
 53                     strpk_name = list_PK[0].PK_Name;
 54                 }
 55             }
 56             strPK = strPK.TrimEnd(‘,‘);
 57             if (dt != null && dt.Rows.Count > 0)
 58             {
 59                 foreach (DataRow dr in dt.Rows)
 60                 {
 61                     TableInfoEntity entity = new TableInfoEntity() ;
 62                     entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t", "");
 63                     entity.ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
 64                     entity.TypeName = dr["TYPE_NAME"].ToString();
 65                     entity.Precision = Convert.ToInt32(dr["PRECISION"].ToString());
 66                     entity.SCALE = dr["SCALE"] == System.DBNull.Value ? 0 : Convert.ToInt32(dr["SCALE"].ToString());
 67                     entity.Nullable = dr["NULLABLE"].ToString().Trim() == "0" ? false : true;
 68                     entity.IsIdentity = dr["TYPE_NAME"].ToString().Contains("identity") ? true : false;
 69                     entity.IsPK = list_PK.Where(q => q.PK_ColumnName == dr["COLUMN_NAME"].ToString()).Count() > 0 ? true : false;
 70                     entity.PKColumn = strPK;
 71                     entity.PK_Name = strpk_name.Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace("\t","").Replace(".","");
 72                     list.Add(entity);
 73                 }
 74             }
 75
 76             return list;
 77         }
 78
 79         /// <summary>
 80         /// 獲取表格的主鍵
 81         /// </summary>
 82         /// <param name="tablename">表格名稱</param>
 83         /// <returns></returns>
 84         public List<TablePKEntity> GetTablePK(string tablename)
 85         {
 86             string strProc = "sp_pkeys";
 87             SqlParameter[] parameters = {
 88                     new SqlParameter("@table_name", SqlDbType.VarChar,50)
 89                                         };
 90             parameters[0].Value = tablename;
 91             DataTable dt = DbHelperSQL.RunProcedure(strProc, parameters, tablename).Tables[0];
 92             List<TablePKEntity> list = new List<TablePKEntity>();
 93             if (dt != null && dt.Rows.Count > 0)
 94             {
 95                 foreach (DataRow dr in dt.Rows)
 96                 {
 97                     TablePKEntity entity = new TablePKEntity();
 98                     entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t","");
 99                     entity.PK_ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
100                     entity.PK_Name = dr["PK_NAME"].ToString();
101                     list.Add(entity);
102                 }
103             }
104             return list;
105         }
106
107         public DataTable GetTableData(string querySql)
108         {
109             DataTable dt = DbHelperSQL.Query(querySql).Tables[0];
110             return dt;
111         }
112
113         public int ExcuteSql(List<string> sql)
114         {
115             return DbHelperSQL.ExecuteSqlTran(sql);
116         }
117     }
118 }

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data.SQLite;
  6 using System.IO;
  7 using System.Data;
  8
  9 namespace SQL2Sqlite
 10 {
 11     public class BaseHelper
 12     {
 13         //日志文件生命周期的时间标记
 14         //private static DateTime TimeSign;
 15         public Dictionary<string, string> dicSqlInsert = new Dictionary<string, string>();
 16         public Dictionary<string, string> dicSqlQuery = new Dictionary<string, string>();
 17         private string GetDBName()
 18         {
 19             DateTime now = DateTime.Now;
 20
 21             string name = "FB_Proposal" + now.ToString("yyyyMMdd") + ".db";
 22             if (!File.Exists(name))
 23             {
 24                 //創建DB
 25                 createNewDatabase(name);
 26                 //創建Table
 27                 //CreateTable(name);
 28             }
 29             return name;
 30         }
 31         //创建一个空的数据库
 32         private void createNewDatabase(string name)
 33         {
 34            SQLiteConnection.CreateFile(name);
 35         }
 36         private void CreateTable(string name)
 37         {
 38             string sql = "create table YouKeyBorad (addtime INTEGER, keyvalue varchar(10));create table YouScreen (addtime INTEGER, screenimg TEXT)";
 39             SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", name));
 40             SQLiteCommand command = new SQLiteCommand(sql, conn);
 41             conn.Open();
 42             command.ExecuteNonQuery();
 43             conn.Close();
 44         }
 45         public SQLiteConnection Connect()
 46         {
 47             SQLiteConnection m_dbConnection = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", GetDBName()));
 48             return m_dbConnection;
 49         }
 50
 51         public  bool CreateTable2(string tablename)
 52         {
 53
 54             bool retbool = false;
 55             StringBuilder strSql = new StringBuilder();
 56             //生成 插入數據的SQl語句
 57             StringBuilder strSql_insert = new StringBuilder();
 58             StringBuilder strSql_Query = new StringBuilder();
 59             try
 60             {
 61                 strSql.Append(" create table ");
 62                 strSql.Append("[" + tablename.TrimEnd() + "]");
 63                 strSql.Append(" ( ");
 64                 DBParse dbSQL = new DBParse();
 65                 List<TableInfoEntity> list = dbSQL.GetTableInfo(tablename);
 66                 //foreach (TableInfoEntity entity in list)
 67                 string strPK = "";
 68                 string strpk_name = "";
 69                 strSql_insert.AppendFormat(" insert into {0} values(", tablename);
 70                 strSql_Query.Append("select ");
 71                 //拼接創建表的SQL
 72                 for (int i = 0; i < list.Count; i++)
 73                 {
 74                     TableInfoEntity entity = list[i];
 75                     #region 拼接創建表 SQL
 76                     strSql.Append("[" + entity.ColumnName + "]");
 77                     strSql.Append(" ");
 78                     strSql.Append(SQLType2SQLiteType.SqlTypeString2SqliteType(entity.TypeName, entity.Precision, entity.SCALE));
 79
 80                     if (!entity.Nullable)
 81                     {
 82                         strSql.Append("  NOT NULL ");
 83                     }
 84
 85                     //if (entity.IsIdentity)
 86                     //{
 87                     //    strSql.Append(" AUTOINCREMENT ");
 88                     //}
 89                     #endregion
 90                     #region 拼接插入數據的SQL
 91                     if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
 92                      || entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
 93                      || entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
 94                      || entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
 95                      || entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
 96                     {
 97                         strSql_insert.Append(" ‘{");
 98                     }
 99                     else
100                     {
101                         strSql_insert.Append(" {");
102                     }
103                     if (entity.TypeName.Equals("System.DateTime") || entity.TypeName.ToLower().Contains("datetime"))
104                     {
105                         strSql_insert.Append(i + ":yyyy-MM-dd HH:mm:ss.fff");
106                     }
107                     else
108                     {
109                         strSql_insert.Append(i);
110                     }
111                     //strSql_insert.Append(i);
112                     if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
113                      || entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
114                      || entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
115                      || entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
116                      || entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
117                     {
118                         strSql_insert.Append("}‘");
119                     }
120                     else
121                     {
122                         strSql_insert.Append("}");
123                     }
124                     #endregion
125                     #region 拼接查詢數據的SQL
126                     strSql_Query.Append("[" + entity.ColumnName + "]");
127                     #endregion
128                     if (i < list.Count - 1)
129                     {
130                         strSql.Append(",");
131                         strSql_insert.Append(",");
132                         strSql_Query.Append(",");
133                     }
134                     strPK = entity.PKColumn;
135                     strpk_name = entity.PK_Name;
136                 }
137                 //給表添加主鍵
138                 if (strPK != "")
139                 {
140                     if (strpk_name.Trim() == "")
141                     {
142                         strpk_name = "pk_" + tablename.TrimEnd();
143                     }
144                     strSql.AppendFormat(" ,constraint {0} primary key ({1}) ", strpk_name, strPK);
145                 }
146                 strSql.Append(" ) ");
147                 strSql_insert.Append(" );");
148                 strSql_Query.Append(" from " + tablename.TrimEnd());
149                 SQLiteHelper.ExecuteNonQuery(Connect(), strSql.ToString());
150                 retbool = true;
151                 dicSqlInsert.Add(tablename.TrimEnd(), strSql_insert.ToString());
152                 dicSqlQuery.Add(tablename.TrimEnd(), strSql_Query.ToString());
153             }
154             catch (Exception ee)
155             {
156                 MyConsole.WriteLine(ee.Message + "----" + strSql.ToString());
157                 retbool = false;
158             }
159             return retbool;
160         }
161
162         public int ImportData(string querySql,string intoSql)
163         {
164             int retInt = 0;
165             DBParse dbSQL = new DBParse();
166             DataTable dtSqlData = dbSQL.GetTableData(querySql);
167             //最後的執行insert的SQL語句
168             List<string> listSql = new List<string>();
169             if (dtSqlData != null && dtSqlData.Rows.Count > 0)
170             {
171                 for (int i = 0; i < dtSqlData.Rows.Count; i++)
172                 {
173                     try
174                     {
175                         string sqlTemp = "";
176                         object[] args = new object[dtSqlData.Columns.Count];
177                         object objtemp = null;
178                         bool haveNull = false;
179                         for (int j = 0; j < dtSqlData.Columns.Count; j++)
180                         {
181                             //MyConsole.TransferEncoding(Encoding.Default, Encoding.UTF8, dtSqlData.Rows[i][j].ToString());
182                             if (intoSql.Contains("PIA_LOG_MAIN"))
183                             {
184                                 break;
185                             }
186                             //if (intoSql.Contains("tbNews"))
187                             //{
188                             //    int x = 0;
189                             //}
190                             if (dtSqlData.Rows[i][j] == DBNull.Value || dtSqlData.Columns[j].DataType == Type.GetType("System.Byte[]"))
191                             {
192                                 args[j] = "Null";
193                                 sqlTemp = intoSql.Replace("‘{" + j + "}‘", "{" + j + "}");
194                                 haveNull = true;
195                             }
196                             else if (dtSqlData.Columns[j].DataType == Type.GetType("System.Boolean"))
197                             {
198                                 args[j] = Convert.ToBoolean(dtSqlData.Rows[i][j]) ? 1 : 0;
199                             }
200                             else
201                             {
202                                 if (dtSqlData.Rows[i][j].ToString().Contains(@"‘"))
203                                 {
204                                     args[j] = dtSqlData.Rows[i][j].ToString().Replace(@"‘", @"‘‘");
205                                 }
206                                 else
207                                 {
208                                     args[j] = dtSqlData.Rows[i][j];
209                                 }
210                             }
211                         }
212                         string into_temp = "";
213                         if (haveNull)
214                         {
215                             into_temp = string.Format(sqlTemp, args);
216                         }
217                         else
218                         {
219                             into_temp = string.Format(intoSql, args);
220                         }
221                         //string into_temp = string.Format(intoSql, args);
222                         listSql.Add(into_temp.Replace("‘Null‘","Null"));
223                         if (listSql.Count == 500)
224                         {
225                             int temp = ExecuteSQL(listSql);
226                             if (temp == 0)
227                             {
228                                 Logger.Error(listSql.ToString());
229                                 MyConsole.WriteLine("有500條導入數據的事務出現異常,已放棄:" + intoSql);
230                             }
231                             retInt += temp;
232                             listSql.Clear();
233                         }
234                     }
235                     catch (Exception ex)
236                     {
237                         MyConsole.WriteLine(ex.Message);
238                     }
239                 }
240                 if (listSql.Count > 0)
241                 {
242                     //retInt += ExecuteSQL(listSql);
243                     int temp = ExecuteSQL(listSql);
244                     if (temp == 0)
245                     {
246                         MyConsole.WriteLine("有部分導入數據的事務出現異常,已放棄:" + intoSql);
247                     }
248                     retInt += temp;
249                 }
250             }
251             return retInt;
252         }
253
254         private int ExecuteSQL(List<string> intoSql)
255         {
256             return SQLiteHelper.ExecuteSqlTran(Connect(),intoSql);
257         }
258
259     }
260 }

從數據庫中得到數據

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data;
  6 using System.Data.SqlClient;
  7
  8 namespace SQL2Sqlite
  9 {
 10     public class DBParse
 11     {
 12         /// <summary>
 13         /// 獲取DB中所有的表格
 14         /// </summary>
 15         /// <returns></returns>
 16         public List<TableEntity> GetAllTable()
 17         {
 18             string sql = "SELECT Name FROM SysObjects Where XType=‘U‘ ORDER BY Name";
 19             DataTable dt = DbHelperSQL.Query(sql).Tables[0];
 20             List<TableEntity> list = new List<TableEntity>();
 21             if (dt != null && dt.Rows.Count > 0)
 22             {
 23                 foreach (DataRow dr in dt.Rows)
 24                 {
 25                     TableEntity entity = new TableEntity() { TableName = dr["Name"].ToString() };
 26                     list.Add(entity);
 27                 }
 28             }
 29
 30             return list;
 31         }
 32
 33         public List<TableInfoEntity> GetTableInfo(string tablename)
 34         {
 35             string strProc = "sp_columns";
 36             SqlParameter[] parameters = {
 37                     new SqlParameter("@table_name", SqlDbType.VarChar,50)
 38                                         };
 39             parameters[0].Value = tablename;
 40             DataTable dt = DbHelperSQL.RunProcedure(strProc,parameters,tablename).Tables[0];
 41             List<TableInfoEntity> list = new List<TableInfoEntity>();
 42             List<TablePKEntity> list_PK = GetTablePK(tablename);
 43             string strPK = "";
 44             string strpk_name = "";
 45             foreach (TablePKEntity pk in list_PK)
 46             {
 47                 strPK += pk.PK_ColumnName + ",";
 48             }
 49             if (list_PK != null && list_PK.Count > 0)
 50             {
 51                 if (!string.IsNullOrWhiteSpace(list_PK[0].PK_Name))
 52                 {
 53                     strpk_name = list_PK[0].PK_Name;
 54                 }
 55             }
 56             strPK = strPK.TrimEnd(‘,‘);
 57             if (dt != null && dt.Rows.Count > 0)
 58             {
 59                 foreach (DataRow dr in dt.Rows)
 60                 {
 61                     TableInfoEntity entity = new TableInfoEntity() ;
 62                     entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t", "");
 63                     entity.ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
 64                     entity.TypeName = dr["TYPE_NAME"].ToString();
 65                     entity.Precision = Convert.ToInt32(dr["PRECISION"].ToString());
 66                     entity.SCALE = dr["SCALE"] == System.DBNull.Value ? 0 : Convert.ToInt32(dr["SCALE"].ToString());
 67                     entity.Nullable = dr["NULLABLE"].ToString().Trim() == "0" ? false : true;
 68                     entity.IsIdentity = dr["TYPE_NAME"].ToString().Contains("identity") ? true : false;
 69                     entity.IsPK = list_PK.Where(q => q.PK_ColumnName == dr["COLUMN_NAME"].ToString()).Count() > 0 ? true : false;
 70                     entity.PKColumn = strPK;
 71                     entity.PK_Name = strpk_name.Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace("\t","").Replace(".","");
 72                     list.Add(entity);
 73                 }
 74             }
 75
 76             return list;
 77         }
 78
 79         /// <summary>
 80         /// 獲取表格的主鍵
 81         /// </summary>
 82         /// <param name="tablename">表格名稱</param>
 83         /// <returns></returns>
 84         public List<TablePKEntity> GetTablePK(string tablename)
 85         {
 86             string strProc = "sp_pkeys";
 87             SqlParameter[] parameters = {
 88                     new SqlParameter("@table_name", SqlDbType.VarChar,50)
 89                                         };
 90             parameters[0].Value = tablename;
 91             DataTable dt = DbHelperSQL.RunProcedure(strProc, parameters, tablename).Tables[0];
 92             List<TablePKEntity> list = new List<TablePKEntity>();
 93             if (dt != null && dt.Rows.Count > 0)
 94             {
 95                 foreach (DataRow dr in dt.Rows)
 96                 {
 97                     TablePKEntity entity = new TablePKEntity();
 98                     entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t","");
 99                     entity.PK_ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
100                     entity.PK_Name = dr["PK_NAME"].ToString();
101                     list.Add(entity);
102                 }
103             }
104             return list;
105         }
106
107         public DataTable GetTableData(string querySql)
108         {
109             DataTable dt = DbHelperSQL.Query(querySql).Tables[0];
110             return dt;
111         }
112
113         public int ExcuteSql(List<string> sql)
114         {
115             return DbHelperSQL.ExecuteSqlTran(sql);
116         }
117     }
118 }

得到表的信息

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5
 6 namespace SQL2Sqlite
 7 {
 8     public class Entity
 9     {
10
11     }
12
13     /// <summary>
14     /// 數據庫內所有的表格
15     /// </summary>
16     public class TableEntity
17     {
18         public string TableName { get; set; }
19     }
20
21     /// <summary>
22     /// 表格對象
23     /// </summary>
24     public class TableInfoEntity
25     {
26         /// <summary>
27         /// 表名
28         /// </summary>
29         public string TableName { get; set; }
30         /// <summary>
31         /// 列名
32         /// </summary>
33         public string ColumnName { get; set; }
34         /// <summary>
35         /// 列類型名
36         /// </summary>
37         public string TypeName { get; set; }
38         /// <summary>
39         /// 列類型的長度
40         /// </summary>
41         public int Precision { get; set; }
42
43         /// <summary>
44         /// 列類型的小數位
45         /// </summary>
46         public int SCALE { get; set; }
47
48         /// <summary>
49         /// 列是否可以為空 true可以為空,false不能為空
50         /// </summary>
51         public bool Nullable { get; set; }
52
53         /// <summary>
54         /// 是否自動增長 true為自動增長
55         /// </summary>
56         public bool IsIdentity { get; set; }
57
58         /// <summary>
59         /// 是否為主鍵  true為主鍵
60         /// </summary>
61         public bool IsPK { get; set; }
62
63         /// <summary>
64         /// 所有的主鍵列,逗號隔開
65         /// </summary>
66         public string PKColumn { get; set; }
67         /// <summary>
68         /// 主鍵名
69         /// </summary>
70         public string PK_Name { get; set; }
71
72     }
73
74     /// <summary>
75     /// 表格主鍵名
76     /// </summary>
77     public class TablePKEntity
78     {
79         /// <summary>
80         /// 表名
81         /// </summary>
82         public string TableName { get; set; }
83         /// <summary>
84         /// 主鍵列名
85         /// </summary>
86         public string PK_ColumnName { get; set; }
87
88         /// <summary>
89         /// 主鍵名
90         /// </summary>
91         public string PK_Name { get; set; }
92     }
93 }

實體

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data.SQLite;
  6 using System.IO;
  7 using System.Data;
  8
  9 namespace SQL2Sqlite
 10 {
 11     public class BaseHelper
 12     {
 13         //日志文件生命周期的时间标记
 14         //private static DateTime TimeSign;
 15         public Dictionary<string, string> dicSqlInsert = new Dictionary<string, string>();
 16         public Dictionary<string, string> dicSqlQuery = new Dictionary<string, string>();
 17         private string GetDBName()
 18         {
 19             DateTime now = DateTime.Now;
 20
 21             string name = "FB_Proposal" + now.ToString("yyyyMMdd") + ".db";
 22             if (!File.Exists(name))
 23             {
 24                 //創建DB
 25                 createNewDatabase(name);
 26                 //創建Table
 27                 //CreateTable(name);
 28             }
 29             return name;
 30         }
 31         //创建一个空的数据库
 32         private void createNewDatabase(string name)
 33         {
 34            SQLiteConnection.CreateFile(name);
 35         }
 36         private void CreateTable(string name)
 37         {
 38             string sql = "create table YouKeyBorad (addtime INTEGER, keyvalue varchar(10));create table YouScreen (addtime INTEGER, screenimg TEXT)";
 39             SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", name));
 40             SQLiteCommand command = new SQLiteCommand(sql, conn);
 41             conn.Open();
 42             command.ExecuteNonQuery();
 43             conn.Close();
 44         }
 45         public SQLiteConnection Connect()
 46         {
 47             SQLiteConnection m_dbConnection = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", GetDBName()));
 48             return m_dbConnection;
 49         }
 50
 51         public  bool CreateTable2(string tablename)
 52         {
 53
 54             bool retbool = false;
 55             StringBuilder strSql = new StringBuilder();
 56             //生成 插入數據的SQl語句
 57             StringBuilder strSql_insert = new StringBuilder();
 58             StringBuilder strSql_Query = new StringBuilder();
 59             try
 60             {
 61                 strSql.Append(" create table ");
 62                 strSql.Append("[" + tablename.TrimEnd() + "]");
 63                 strSql.Append(" ( ");
 64                 DBParse dbSQL = new DBParse();
 65                 List<TableInfoEntity> list = dbSQL.GetTableInfo(tablename);
 66                 //foreach (TableInfoEntity entity in list)
 67                 string strPK = "";
 68                 string strpk_name = "";
 69                 strSql_insert.AppendFormat(" insert into {0} values(", tablename);
 70                 strSql_Query.Append("select ");
 71                 //拼接創建表的SQL
 72                 for (int i = 0; i < list.Count; i++)
 73                 {
 74                     TableInfoEntity entity = list[i];
 75                     #region 拼接創建表 SQL
 76                     strSql.Append("[" + entity.ColumnName + "]");
 77                     strSql.Append(" ");
 78                     strSql.Append(SQLType2SQLiteType.SqlTypeString2SqliteType(entity.TypeName, entity.Precision, entity.SCALE));
 79
 80                     if (!entity.Nullable)
 81                     {
 82                         strSql.Append("  NOT NULL ");
 83                     }
 84
 85                     //if (entity.IsIdentity)
 86                     //{
 87                     //    strSql.Append(" AUTOINCREMENT ");
 88                     //}
 89                     #endregion
 90                     #region 拼接插入數據的SQL
 91                     if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
 92                      || entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
 93                      || entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
 94                      || entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
 95                      || entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
 96                     {
 97                         strSql_insert.Append(" ‘{");
 98                     }
 99                     else
100                     {
101                         strSql_insert.Append(" {");
102                     }
103                     if (entity.TypeName.Equals("System.DateTime") || entity.TypeName.ToLower().Contains("datetime"))
104                     {
105                         strSql_insert.Append(i + ":yyyy-MM-dd HH:mm:ss.fff");
106                     }
107                     else
108                     {
109                         strSql_insert.Append(i);
110                     }
111                     //strSql_insert.Append(i);
112                     if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
113                      || entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
114                      || entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
115                      || entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
116                      || entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
117                     {
118                         strSql_insert.Append("}‘");
119                     }
120                     else
121                     {
122                         strSql_insert.Append("}");
123                     }
124                     #endregion
125                     #region 拼接查詢數據的SQL
126                     strSql_Query.Append("[" + entity.ColumnName + "]");
127                     #endregion
128                     if (i < list.Count - 1)
129                     {
130                         strSql.Append(",");
131                         strSql_insert.Append(",");
132                         strSql_Query.Append(",");
133                     }
134                     strPK = entity.PKColumn;
135                     strpk_name = entity.PK_Name;
136                 }
137                 //給表添加主鍵
138                 if (strPK != "")
139                 {
140                     if (strpk_name.Trim() == "")
141                     {
142                         strpk_name = "pk_" + tablename.TrimEnd();
143                     }
144                     strSql.AppendFormat(" ,constraint {0} primary key ({1}) ", strpk_name, strPK);
145                 }
146                 strSql.Append(" ) ");
147                 strSql_insert.Append(" );");
148                 strSql_Query.Append(" from " + tablename.TrimEnd());
149                 SQLiteHelper.ExecuteNonQuery(Connect(), strSql.ToString());
150                 retbool = true;
151                 dicSqlInsert.Add(tablename.TrimEnd(), strSql_insert.ToString());
152                 dicSqlQuery.Add(tablename.TrimEnd(), strSql_Query.ToString());
153             }
154             catch (Exception ee)
155             {
156                 MyConsole.WriteLine(ee.Message + "----" + strSql.ToString());
157                 retbool = false;
158             }
159             return retbool;
160         }
161
162         public int ImportData(string querySql,string intoSql)
163         {
164             int retInt = 0;
165             DBParse dbSQL = new DBParse();
166             DataTable dtSqlData = dbSQL.GetTableData(querySql);
167             //最後的執行insert的SQL語句
168             List<string> listSql = new List<string>();
169             if (dtSqlData != null && dtSqlData.Rows.Count > 0)
170             {
171                 for (int i = 0; i < dtSqlData.Rows.Count; i++)
172                 {
173                     try
174                     {
175                         string sqlTemp = "";
176                         object[] args = new object[dtSqlData.Columns.Count];
177                         object objtemp = null;
178                         bool haveNull = false;
179                         for (int j = 0; j < dtSqlData.Columns.Count; j++)
180                         {
181                             //MyConsole.TransferEncoding(Encoding.Default, Encoding.UTF8, dtSqlData.Rows[i][j].ToString());
182                             if (intoSql.Contains("PIA_LOG_MAIN"))
183                             {
184                                 break;
185                             }
186                             //if (intoSql.Contains("tbNews"))
187                             //{
188                             //    int x = 0;
189                             //}
190                             if (dtSqlData.Rows[i][j] == DBNull.Value || dtSqlData.Columns[j].DataType == Type.GetType("System.Byte[]"))
191                             {
192                                 args[j] = "Null";
193                                 sqlTemp = intoSql.Replace("‘{" + j + "}‘", "{" + j + "}");
194                                 haveNull = true;
195                             }
196                             else if (dtSqlData.Columns[j].DataType == Type.GetType("System.Boolean"))
197                             {
198                                 args[j] = Convert.ToBoolean(dtSqlData.Rows[i][j]) ? 1 : 0;
199                             }
200                             else
201                             {
202                                 if (dtSqlData.Rows[i][j].ToString().Contains(@"‘"))
203                                 {
204                                     args[j] = dtSqlData.Rows[i][j].ToString().Replace(@"‘", @"‘‘");
205                                 }
206                                 else
207                                 {
208                                     args[j] = dtSqlData.Rows[i][j];
209                                 }
210                             }
211                         }
212                         string into_temp = "";
213                         if (haveNull)
214                         {
215                             into_temp = string.Format(sqlTemp, args);
216                         }
217                         else
218                         {
219                             into_temp = string.Format(intoSql, args);
220                         }
221                         //string into_temp = string.Format(intoSql, args);
222                         listSql.Add(into_temp.Replace("‘Null‘","Null"));
223                         if (listSql.Count == 500)
224                         {
225                             int temp = ExecuteSQL(listSql);
226                             if (temp == 0)
227                             {
228                                 Logger.Error(listSql.ToString());
229                                 MyConsole.WriteLine("有500條導入數據的事務出現異常,已放棄:" + intoSql);
230                             }
231                             retInt += temp;
232                             listSql.Clear();
233                         }
234                     }
235                     catch (Exception ex)
236                     {
237                         MyConsole.WriteLine(ex.Message);
238                     }
239                 }
240                 if (listSql.Count > 0)
241                 {
242                     //retInt += ExecuteSQL(listSql);
243                     int temp = ExecuteSQL(listSql);
244                     if (temp == 0)
245                     {
246                         MyConsole.WriteLine("有部分導入數據的事務出現異常,已放棄:" + intoSql);
247                     }
248                     retInt += temp;
249                 }
250             }
251             return retInt;
252         }
253
254         private int ExecuteSQL(List<string> intoSql)
255         {
256             return SQLiteHelper.ExecuteSqlTran(Connect(),intoSql);
257         }
258
259     }
260 }

DBHelper

时间: 2024-10-08 02:11:53

使用entitiy的相关文章

Android学习笔记-构建一个可复用的自定义BaseAdapter

转载自http://www.runoob.com/w3cnote/android-tutorial-customer-baseadapter.html   作者:coder-pig 本节引言: 如题,本节给大家带来的是构建一个可复用的自定义BaseAdapter,我们每每涉及到ListView GridView等其他的Adapter控件,都需要自己另外写一个BaseAdapter类,这样显得非常麻烦, 又比如,我们想在一个界面显示两个ListView的话,我们也是需要些两个BaseAdapter

LINQ的左连接、右连接、内连接

1.左连接: var LeftJoin = from emp in ListOfEmployees join dept in ListOfDepartment on emp.DeptID equals dept.ID into JoinedEmpDept from dept in JoinedEmpDept.DefaultIfEmpty() select new { EmployeeName = emp.Name, DepartmentName = dept != null ? dept.Nam

总结一下工作中用到的Mybatis业务逻辑

1.简单说明. MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录. 什么是Mapper对象?根据Mybatis的官方手册,应用程序除了要初始并启动Mybatis之外,还需要定义一些接口,接口里定义访问数据库的方法,存放接口的包路径下需要放置同名的XML配置文件.每个mapper元素对应一个mapper配置文件. 1 <?xml version="1.0

hostapd wpa_supplicant madwifi详细分析(十三)——EAPOL(802.1X-2004/IEEE Std 802.1X-2010)

这篇文章主要介绍EAPOL,关于它的详细定义可以到802.1X-2004/IEEE Std 802.1X-2010两个文档里面查询.这两个文档核心内容大同小异,只是2010版定义得更细致,同时也更难以理解,建议先了解2004版,会更容易看懂.因为2010版引入来更多的名词,加入了更多的参考资料,对一致性的描述更加细致具体,让标准可以适用于更多的加密场合,补充2004 版中的一下缺陷. 两个标准的前5章的差异,我们可以不用太深究,他们主要包括802.1x的定义,名词解释,适用范围,引用文档,一致性

MEF实现设计上的“松耦合”(二)

介绍了下MEF的基础用法,让我们对MEF有了一个抽象的认识.当然MEF的用法可能不限于此,比如MEF的目录服务.目录筛选.重组部件等高级应用在这里就不做过多讲解,因为博主觉得这些用法只有在某些特定的环境下面才会用到,着实不太普遍,感觉没有钻下去的必要.如果你有兴趣也可以去了解下.这篇打算将MEF和仓储模式结合起来谈谈MEF在项目中的使用. 1.仓储模式:也叫Repository模式.Repository是一个独立的层,介于领域层与数据映射层(数据访问层)之间.它的存在让领域层感觉不到数据访问层的

【转载】Ogre:Beginner Tutorial 1: SceneNode, Entity,和SceneManager 结构

原文:Beginner Tutorial 1: SceneNode, Entity,和SceneManager 结构 先决条件 这个教程假设你有C++编程的基础并且可以配置并编译OGRE应用程序 (如果你在配置环境方面有问题,请看OGRE + MinGW + Code::Blocks环境的搭建). 除了配置环境之外,你不需要有任何关于OGRE的知识. 介绍 在这个教程中,我会介绍给你OGRE中最基本的结构: SceneManager, SceneNode, 还有Entity 对象.我们不会涉及大

使用PowerDesigner画ER图详细教程

转:http://www.360doc.com/content/11/0624/15/2617151_129276457.shtml 一.概念数据模型概述数据模型是现实世界中数据特征的抽象.数据模型应该满足三个方面的要求:1)能够比较真实地模拟现实世界2)容易为人所理解3)便于计算机实现 概念数据模型也称信息模型,它以实体-联系(Entity-RelationShip,简称E-R)理论为基础,并对这一理论进行了扩充.它从用户的观点出发对信息进行建模,主要用于数据库的概念级设计. 通 常人们先将现

PowerDesigner教程 —— 概念数据模型 (转)

一.概念数据模型概述     概念数据模型也称信息模型,它以实体-联系(Entity-RelationShip,简称E-R)理论为基础,并对这一理论进行了扩充.它从用户的观点出发对信息进行建模,主要用于数据库的概念级设计. 通常人们先将现实世界抽象为概念世界,然后再将概念世界转为机器世界.换句话说,就是先将现实世界中的客观对象抽象为实体(Entity)和联系 (Relationship),它并不依赖于具体的计算机系统或某个DBMS系统,这种模型就是我们所说的CDM;然后再将CDM转换为计算机上某

Android两个ListView共用一个万能的BaseAdapter

Android两个ListView共用一个万能的BaseAdapter 升级之前的MyAdapter.java package run.yang.com.listviewactivedemo; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAd