使用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 }
View Code
  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 }
得到SQL插入语句

 

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Specialized;
  4 using System.Data;
  5 using System.Data.SqlClient;
  6 using System.Configuration;
  7 using System.Data.Common;
  8 using System.Collections.Generic;
  9 namespace SQL2Sqlite
 10 {
 11     /// <summary>
 12     /// 数据访问抽象基础类
 13     /// Copyright (C) Maticsoft
 14     /// </summary>
 15     public abstract class DbHelperSQL
 16     {
 17         //数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现.
 18         private static string connectionString = ConfigurationManager.AppSettings["DefaultConnection"].ToString();//PubConstant.ConnectionString;             
 19 
 20         public static string ConnectionString
 21         {
 22             get { return connectionString;/*DbHelperSQL.connectionString;*/ }
 23             //set { DbHelperSQL.connectionString = value; }
 24         }
 25         public DbHelperSQL()
 26         {
 27         }
 28 
 29         
 30 
 31         #region 公用方法
 32 
 33         
 34 
 35         /// <summary>
 36         /// 判断是否存在某表的某个字段
 37         /// </summary>
 38         /// <param name="tableName">表名称</param>
 39         /// <param name="columnName">列名称</param>
 40         /// <returns>是否存在</returns>
 41         public static bool ColumnExists(string tableName, string columnName)
 42         {
 43             string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
 44             object res = GetSingle(sql);
 45             if (res == null)
 46             {
 47                 return false;
 48             }
 49             return Convert.ToInt32(res) > 0;
 50         }
 51         public static int GetMaxID(string FieldName, string TableName)
 52         {
 53             string strsql = "select max(" + FieldName + ")+1 from " + TableName;
 54             object obj = GetSingle(strsql);
 55             if (obj == null)
 56             {
 57                 return 1;
 58             }
 59             else
 60             {
 61                 return int.Parse(obj.ToString());
 62             }
 63         }
 64         public static bool Exists(string strSql)
 65         {
 66             object obj = GetSingle(strSql);
 67             int cmdresult;
 68             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
 69             {
 70                 cmdresult = 0;
 71             }
 72             else
 73             {
 74                 cmdresult = int.Parse(obj.ToString());
 75             }
 76             if (cmdresult == 0)
 77             {
 78                 return false;
 79             }
 80             else
 81             {
 82                 return true;
 83             }
 84         }
 85         /// <summary>
 86         /// 表是否存在
 87         /// </summary>
 88         /// <param name="TableName"></param>
 89         /// <returns></returns>
 90         public static bool TabExists(string TableName)
 91         {
 92             string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
 93             //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
 94             object obj = GetSingle(strsql);
 95             int cmdresult;
 96             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
 97             {
 98                 cmdresult = 0;
 99             }
100             else
101             {
102                 cmdresult = int.Parse(obj.ToString());
103             }
104             if (cmdresult == 0)
105             {
106                 return false;
107             }
108             else
109             {
110                 return true;
111             }
112         }
113         public static bool Exists(string strSql, params SqlParameter[] cmdParms)
114         {
115             object obj = GetSingle(strSql, cmdParms);
116             int cmdresult;
117             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
118             {
119                 cmdresult = 0;
120             }
121             else
122             {
123                 cmdresult = int.Parse(obj.ToString());
124             }
125             if (cmdresult == 0)
126             {
127                 return false;
128             }
129             else
130             {
131                 return true;
132             }
133         }
134         #endregion
135 
136         #region  执行简单SQL语句
137 
138         /// <summary>
139         /// 执行SQL语句,返回影响的记录数
140         /// </summary>
141         /// <param name="SQLString">SQL语句</param>
142         /// <returns>影响的记录数</returns>
143         public static int ExecuteSql(string SQLString)
144         {
145             using (SqlConnection connection = new SqlConnection(connectionString))
146             {
147                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))
148                 {
149                     try
150                     {
151                         connection.Open();
152                         int rows = cmd.ExecuteNonQuery();
153                         return rows;
154                     }
155                     catch (System.Data.SqlClient.SqlException e)
156                     {
157                         connection.Close();
158                         throw e;
159                     }
160                 }
161             }
162         }
163 
164         public static int ExecuteSqlByTime(string SQLString, int Times)
165         {
166             using (SqlConnection connection = new SqlConnection(connectionString))
167             {
168                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))
169                 {
170                     try
171                     {
172                         connection.Open();
173                         cmd.CommandTimeout = Times;
174                         int rows = cmd.ExecuteNonQuery();
175                         return rows;
176                     }
177                     catch (System.Data.SqlClient.SqlException e)
178                     {
179                         connection.Close();
180                         throw e;
181                     }
182                 }
183             }
184         }
185       
186              
187         /// <summary>
188         /// 执行多条SQL语句,实现数据库事务。
189         /// </summary>
190         /// <param name="SQLStringList">多条SQL语句</param>        
191         public static int ExecuteSqlTran(List<String> SQLStringList)
192         {
193             using (SqlConnection conn = new SqlConnection(connectionString))
194             {
195                 conn.Open();
196                 SqlCommand cmd = new SqlCommand();
197                 cmd.Connection = conn;
198                 SqlTransaction tx = conn.BeginTransaction();
199                 cmd.Transaction = tx;
200                 try
201                 {
202                     int count = 0;
203                     for (int n = 0; n < SQLStringList.Count; n++)
204                     {
205                         string strsql = SQLStringList[n];
206                         if (strsql.Trim().Length > 1)
207                         {
208                             cmd.CommandText = strsql;
209                             count += cmd.ExecuteNonQuery();
210                         }
211                     }
212                     tx.Commit();
213                     return count;
214                 }
215                 catch
216                 {
217                     tx.Rollback();
218                     return 0;
219                 }
220             }
221         }
222         /// <summary>
223         /// 执行带一个存储过程参数的的SQL语句。
224         /// </summary>
225         /// <param name="SQLString">SQL语句</param>
226         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
227         /// <returns>影响的记录数</returns>
228         public static int ExecuteSql(string SQLString, string content)
229         {
230             using (SqlConnection connection = new SqlConnection(connectionString))
231             {
232                 SqlCommand cmd = new SqlCommand(SQLString, connection);
233                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
234                 myParameter.Value = content;
235                 cmd.Parameters.Add(myParameter);
236                 try
237                 {
238                     connection.Open();
239                     int rows = cmd.ExecuteNonQuery();
240                     return rows;
241                 }
242                 catch (System.Data.SqlClient.SqlException e)
243                 {
244                     throw e;
245                 }
246                 finally
247                 {
248                     cmd.Dispose();
249                     connection.Close();
250                 }
251             }
252         }
253         /// <summary>
254         /// 执行带一个存储过程参数的的SQL语句。
255         /// </summary>
256         /// <param name="SQLString">SQL语句</param>
257         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
258         /// <returns>影响的记录数</returns>
259         public static object ExecuteSqlGet(string SQLString, string content)
260         {
261             using (SqlConnection connection = new SqlConnection(connectionString))
262             {
263                 SqlCommand cmd = new SqlCommand(SQLString, connection);
264                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
265                 myParameter.Value = content;
266                 cmd.Parameters.Add(myParameter);
267                 try
268                 {
269                     connection.Open();
270                     object obj = cmd.ExecuteScalar();
271                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
272                     {
273                         return null;
274                     }
275                     else
276                     {
277                         return obj;
278                     }
279                 }
280                 catch (System.Data.SqlClient.SqlException e)
281                 {
282                     throw e;
283                 }
284                 finally
285                 {
286                     cmd.Dispose();
287                     connection.Close();
288                 }
289             }
290         }
291         /// <summary>
292         /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
293         /// </summary>
294         /// <param name="strSQL">SQL语句</param>
295         /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
296         /// <returns>影响的记录数</returns>
297         public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
298         {
299             using (SqlConnection connection = new SqlConnection(connectionString))
300             {
301                 SqlCommand cmd = new SqlCommand(strSQL, connection);
302                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
303                 myParameter.Value = fs;
304                 cmd.Parameters.Add(myParameter);
305                 try
306                 {
307                     connection.Open();
308                     int rows = cmd.ExecuteNonQuery();
309                     return rows;
310                 }
311                 catch (System.Data.SqlClient.SqlException e)
312                 {
313                     throw e;
314                 }
315                 finally
316                 {
317                     cmd.Dispose();
318                     connection.Close();
319                 }
320             }
321         }
322 
323         /// <summary>
324         /// 执行一条计算查询结果语句,返回查询结果(object)。
325         /// </summary>
326         /// <param name="SQLString">计算查询结果语句</param>
327         /// <returns>查询结果(object)</returns>
328         public static object GetSingle(string SQLString)
329         {
330             using (SqlConnection connection = new SqlConnection(connectionString))
331             {
332                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))
333                 {
334                     try
335                     {
336                         connection.Open();
337                         object obj = cmd.ExecuteScalar();
338                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
339                         {
340                             return null;
341                         }
342                         else
343                         {
344                             return obj;
345                         }
346                     }
347                     catch (System.Data.SqlClient.SqlException e)
348                     {
349                         connection.Close();
350                         throw e;
351                     }
352                 }
353             }
354         }
355         public static object GetSingle(string SQLString, int Times)
356         {
357             using (SqlConnection connection = new SqlConnection(connectionString))
358             {
359                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))
360                 {
361                     try
362                     {
363                         connection.Open();
364                         cmd.CommandTimeout = Times;
365                         object obj = cmd.ExecuteScalar();
366                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
367                         {
368                             return null;
369                         }
370                         else
371                         {
372                             return obj;
373                         }
374                     }
375                     catch (System.Data.SqlClient.SqlException e)
376                     {
377                         connection.Close();
378                         throw e;
379                     }
380                 }
381             }
382         }
383         /// <summary>
384         /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
385         /// </summary>
386         /// <param name="strSQL">查询语句</param>
387         /// <returns>SqlDataReader</returns>
388         public static SqlDataReader ExecuteReader(string strSQL)
389         {
390             SqlConnection connection = new SqlConnection(connectionString);
391             SqlCommand cmd = new SqlCommand(strSQL, connection);
392             try
393             {
394                 connection.Open();
395                 SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
396                 return myReader;
397             }
398             catch (System.Data.SqlClient.SqlException e)
399             {
400                 throw e;
401             }   
402 
403         }
404         /// <summary>
405         /// 执行查询语句,返回DataSet
406         /// </summary>
407         /// <param name="SQLString">查询语句</param>
408         /// <returns>DataSet</returns>
409         public static DataSet Query(string SQLString)
410         {
411             using (SqlConnection connection = new SqlConnection(connectionString))
412             {
413                 DataSet ds = new DataSet();
414                 try
415                 {
416                     connection.Open();
417                     SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
418                     command.Fill(ds, "ds");
419                 }
420                 catch (System.Data.SqlClient.SqlException ex)
421                 {
422                     throw new Exception(ex.Message);
423                 }
424                 return ds;
425             }
426         }
427         public static DataSet Query(string SQLString, int Times)
428         {
429             using (SqlConnection connection = new SqlConnection(connectionString))
430             {
431                 DataSet ds = new DataSet();
432                 try
433                 {
434                     connection.Open();
435                     SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
436                     command.SelectCommand.CommandTimeout = Times;
437                     command.Fill(ds, "ds");
438                 }
439                 catch (System.Data.SqlClient.SqlException ex)
440                 {
441                     throw new Exception(ex.Message);
442                 }
443                 return ds;
444             }
445         }
446 
447 
448 
449         #endregion
450 
451         #region 执行带参数的SQL语句
452 
453         /// <summary>
454         /// 执行SQL语句,返回影响的记录数
455         /// </summary>
456         /// <param name="SQLString">SQL语句</param>
457         /// <returns>影响的记录数</returns>
458         public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
459         {
460             using (SqlConnection connection = new SqlConnection(connectionString))
461             {
462                 using (SqlCommand cmd = new SqlCommand())
463                 {
464                     try
465                     {
466                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);
467                         int rows = cmd.ExecuteNonQuery();
468                         cmd.Parameters.Clear();
469                         return rows;
470                     }
471                     catch (System.Data.SqlClient.SqlException e)
472                     {
473                         throw e;
474                     }
475                 }
476             }
477         }
478 
479 
480         /// <summary>
481         /// 执行多条SQL语句,实现数据库事务。
482         /// </summary>
483         /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
484         public static void ExecuteSqlTran(Hashtable SQLStringList)
485         {
486             using (SqlConnection conn = new SqlConnection(connectionString))
487             {
488                 conn.Open();
489                 using (SqlTransaction trans = conn.BeginTransaction())
490                 {
491                     SqlCommand cmd = new SqlCommand();
492                     try
493                     {
494                         //循环
495                         foreach (DictionaryEntry myDE in SQLStringList)
496                         {
497                             string cmdText = myDE.Key.ToString();
498                             SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
499                             PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
500                             int val = cmd.ExecuteNonQuery();
501                             cmd.Parameters.Clear();
502                         }
503                         trans.Commit();
504                     }
505                     catch
506                     {
507                         trans.Rollback();
508                         throw;
509                     }
510                 }
511             }
512         }
513         ///// <summary>
514         ///// 执行多条SQL语句,实现数据库事务。
515         ///// </summary>
516         ///// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
517         //public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
518         //{
519         //    using (SqlConnection conn = new SqlConnection(connectionString))
520         //    {
521         //        conn.Open();
522         //        using (SqlTransaction trans = conn.BeginTransaction())
523         //        {
524         //            SqlCommand cmd = new SqlCommand();
525         //            try
526         //            { int count = 0;
527         //                //循环
528         //                foreach (CommandInfo myDE in cmdList)
529         //                {
530         //                    string cmdText = myDE.CommandText;
531         //                    SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
532         //                    PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
533                            
534         //                    if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
535         //                    {
536         //                        if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
537         //                        {
538         //                            trans.Rollback();
539         //                            return 0;
540         //                        }
541 
542         //                        object obj = cmd.ExecuteScalar();
543         //                        bool isHave = false;
544         //                        if (obj == null && obj == DBNull.Value)
545         //                        {
546         //                            isHave = false;
547         //                        }
548         //                        isHave = Convert.ToInt32(obj) > 0;
549 
550         //                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
551         //                        {
552         //                            trans.Rollback();
553         //                            return 0;
554         //                        }
555         //                        if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
556         //                        {
557         //                            trans.Rollback();
558         //                            return 0;
559         //                        }
560         //                        continue;
561         //                    }
562         //                    int val = cmd.ExecuteNonQuery();
563         //                    count += val;
564         //                    if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
565         //                    {
566         //                        trans.Rollback();
567         //                        return 0;
568         //                    }
569         //                    cmd.Parameters.Clear();
570         //                }
571         //                trans.Commit();
572         //                return count;
573         //            }
574         //            catch
575         //            {
576         //                trans.Rollback();
577         //                throw;
578         //            }
579         //        }
580         //    }
581         //}
582         ///// <summary>
583         ///// 执行多条SQL语句,实现数据库事务。
584         ///// </summary>
585         ///// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
586         //public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
587         //{
588         //    using (SqlConnection conn = new SqlConnection(connectionString))
589         //    {
590         //        conn.Open();
591         //        using (SqlTransaction trans = conn.BeginTransaction())
592         //        {
593         //            SqlCommand cmd = new SqlCommand();
594         //            try
595         //            {
596         //                int indentity = 0;
597         //                //循环
598         //                foreach (CommandInfo myDE in SQLStringList)
599         //                {
600         //                    string cmdText = myDE.CommandText;
601         //                    SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
602         //                    foreach (SqlParameter q in cmdParms)
603         //                    {
604         //                        if (q.Direction == ParameterDirection.InputOutput)
605         //                        {
606         //                            q.Value = indentity;
607         //                        }
608         //                    }
609         //                    PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
610         //                    int val = cmd.ExecuteNonQuery();
611         //                    foreach (SqlParameter q in cmdParms)
612         //                    {
613         //                        if (q.Direction == ParameterDirection.Output)
614         //                        {
615         //                            indentity = Convert.ToInt32(q.Value);
616         //                        }
617         //                    }
618         //                    cmd.Parameters.Clear();
619         //                }
620         //                trans.Commit();
621         //            }
622         //            catch
623         //            {
624         //                trans.Rollback();
625         //                throw;
626         //            }
627         //        }
628         //    }
629         //}
630         /// <summary>
631         /// 执行多条SQL语句,实现数据库事务。
632         /// </summary>
633         /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
634         public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
635         {
636             using (SqlConnection conn = new SqlConnection(connectionString))
637             {
638                 conn.Open();
639                 using (SqlTransaction trans = conn.BeginTransaction())
640                 {
641                     SqlCommand cmd = new SqlCommand();
642                     try
643                     {
644                         int indentity = 0;
645                         //循环
646                         foreach (DictionaryEntry myDE in SQLStringList)
647                         {
648                             string cmdText = myDE.Key.ToString();
649                             SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
650                             foreach (SqlParameter q in cmdParms)
651                             {
652                                 if (q.Direction == ParameterDirection.InputOutput)
653                                 {
654                                     q.Value = indentity;
655                                 }
656                             }
657                             PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
658                             int val = cmd.ExecuteNonQuery();
659                             foreach (SqlParameter q in cmdParms)
660                             {
661                                 if (q.Direction == ParameterDirection.Output)
662                                 {
663                                     indentity = Convert.ToInt32(q.Value);
664                                 }
665                             }
666                             cmd.Parameters.Clear();
667                         }
668                         trans.Commit();
669                     }
670                     catch
671                     {
672                         trans.Rollback();
673                         throw;
674                     }
675                 }
676             }
677         }
678         /// <summary>
679         /// 执行一条计算查询结果语句,返回查询结果(object)。
680         /// </summary>
681         /// <param name="SQLString">计算查询结果语句</param>
682         /// <returns>查询结果(object)</returns>
683         public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
684         {
685             using (SqlConnection connection = new SqlConnection(connectionString))
686             {
687                 using (SqlCommand cmd = new SqlCommand())
688                 {
689                     try
690                     {
691                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);
692                         object obj = cmd.ExecuteScalar();
693                         cmd.Parameters.Clear();
694                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
695                         {
696                             return null;
697                         }
698                         else
699                         {
700                             return obj;
701                         }
702                     }
703                     catch (System.Data.SqlClient.SqlException e)
704                     {
705                         throw e;
706                     }
707                 }
708             }
709         }
710 
711         /// <summary>
712         /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
713         /// </summary>
714         /// <param name="strSQL">查询语句</param>
715         /// <returns>SqlDataReader</returns>
716         public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
717         {
718             SqlConnection connection = new SqlConnection(connectionString);
719             SqlCommand cmd = new SqlCommand();
720             try
721             {
722                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
723                 SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
724                 cmd.Parameters.Clear();
725                 return myReader;
726             }
727             catch (System.Data.SqlClient.SqlException e)
728             {
729                 throw e;
730             }
731             //            finally
732             //            {
733             //                cmd.Dispose();
734             //                connection.Close();
735             //            }    
736 
737         }
738 
739         /// <summary>
740         /// 执行查询语句,返回DataSet
741         /// </summary>
742         /// <param name="SQLString">查询语句</param>
743         /// <returns>DataSet</returns>
744         public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
745         {
746             using (SqlConnection connection = new SqlConnection(connectionString))
747             {
748                 SqlCommand cmd = new SqlCommand();
749                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
750                 using (SqlDataAdapter da = new SqlDataAdapter(cmd))
751                 {
752                     DataSet ds = new DataSet();
753                     try
754                     {
755                         da.Fill(ds, "ds");
756                         cmd.Parameters.Clear();
757                     }
758                     catch (System.Data.SqlClient.SqlException ex)
759                     {
760                         throw new Exception(ex.Message);
761                     }
762                     return ds;
763                 }
764             }
765         }
766 
767 
768         private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
769         {
770             if (conn.State != ConnectionState.Open)
771                 conn.Open();
772             cmd.Connection = conn;
773             cmd.CommandText = cmdText;
774             if (trans != null)
775                 cmd.Transaction = trans;
776             cmd.CommandType = CommandType.Text;//cmdType;
777             if (cmdParms != null)
778             {
779 
780 
781                 foreach (SqlParameter parameter in cmdParms)
782                 {
783                     if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
784                         (parameter.Value == null))
785                     {
786                         parameter.Value = DBNull.Value;
787                     }
788                     cmd.Parameters.Add(parameter);
789                 }
790             }
791         }
792 
793         #endregion
794 
795         #region 存储过程操作
796 
797         /// <summary>
798         /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
799         /// </summary>
800         /// <param name="storedProcName">存储过程名</param>
801         /// <param name="parameters">存储过程参数</param>
802         /// <returns>SqlDataReader</returns>
803         public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
804         {
805             SqlConnection connection = new SqlConnection(connectionString);
806             SqlDataReader returnReader;
807             connection.Open();
808             SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
809             command.CommandType = CommandType.StoredProcedure;
810             returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
811             return returnReader;
812             
813         }
814 
815 
816         /// <summary>
817         /// 执行存储过程
818         /// </summary>
819         /// <param name="storedProcName">存储过程名</param>
820         /// <param name="parameters">存储过程参数</param>
821         /// <param name="tableName">DataSet结果中的表名</param>
822         /// <returns>DataSet</returns>
823         public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
824         {
825             using (SqlConnection connection = new SqlConnection(connectionString))
826             {
827                 DataSet dataSet = new DataSet();
828                 connection.Open();
829                 SqlDataAdapter sqlDA = new SqlDataAdapter();
830                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
831                 sqlDA.Fill(dataSet, tableName);
832                 connection.Close();
833                 return dataSet;
834             }
835         }
836         public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
837         {
838             using (SqlConnection connection = new SqlConnection(connectionString))
839             {
840                 DataSet dataSet = new DataSet();
841                 connection.Open();
842                 SqlDataAdapter sqlDA = new SqlDataAdapter();
843                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
844                 sqlDA.SelectCommand.CommandTimeout = Times;
845                 sqlDA.Fill(dataSet, tableName);
846                 connection.Close();
847                 return dataSet;
848             }
849         }
850 
851 
852         /// <summary>
853         /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
854         /// </summary>
855         /// <param name="connection">数据库连接</param>
856         /// <param name="storedProcName">存储过程名</param>
857         /// <param name="parameters">存储过程参数</param>
858         /// <returns>SqlCommand</returns>
859         private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
860         {
861             SqlCommand command = new SqlCommand(storedProcName, connection);
862             command.CommandType = CommandType.StoredProcedure;
863             foreach (SqlParameter parameter in parameters)
864             {
865                 if (parameter != null)
866                 {
867                     // 检查未分配值的输出参数,将其分配以DBNull.Value.
868                     if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
869                         (parameter.Value == null))
870                     {
871                         parameter.Value = DBNull.Value;
872                     }
873                     command.Parameters.Add(parameter);
874                 }
875             }
876 
877             return command;
878         }
879 
880         /// <summary>
881         /// 执行存储过程,返回影响的行数        
882         /// </summary>
883         /// <param name="storedProcName">存储过程名</param>
884         /// <param name="parameters">存储过程参数</param>
885         /// <param name="rowsAffected">影响的行数</param>
886         /// <returns></returns>
887         public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
888         {
889             using (SqlConnection connection = new SqlConnection(connectionString))
890             {
891                 int result;
892                 connection.Open();
893                 SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
894                 rowsAffected = command.ExecuteNonQuery();
895                 result = (int)command.Parameters["ReturnValue"].Value;
896                 //Connection.Close();
897                 return result;
898             }
899         }
900 
901         /// <summary>
902         /// 创建 SqlCommand 对象实例(用来返回一个整数值)    
903         /// </summary>
904         /// <param name="storedProcName">存储过程名</param>
905         /// <param name="parameters">存储过程参数</param>
906         /// <returns>SqlCommand 对象实例</returns>
907         private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
908         {
909             SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
910             command.Parameters.Add(new SqlParameter("ReturnValue",
911                 SqlDbType.Int, 4, ParameterDirection.ReturnValue,
912                 false, 0, 0, string.Empty, DataRowVersion.Default, null));
913             return command;
914         }
915         #endregion
916 
917     }
918 
919 }
DBHelper

 

posted @ 2017-03-21 14:20  wonderfulviews  阅读(270)  评论(0编辑  收藏  举报