1
yhj
2024-07-24 5e5d945e91568b973faa27d8ab0bcef99fc4a6c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
#region
 
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
using CSFramework.DB.Common;
using CSFramework.DB.Models;
 
#endregion
 
namespace CSFramework.DB
{
    public class DatabaseMSSQL : IDatabase
    {
        private string _ConnectionString;
 
        public DatabaseMSSQL(string connectionString)
        {
            _ConnectionString = connectionString;
        }
 
        public string BuildConnectionString(string server, int port,
            string dbName, string uid, string pwd,
            int timeout = 15)
        {
            const string DEF_SQL_CONNECTION =
                @"Data Source={0};Initial Catalog={1};User ID={2};Password ={3};Persist Security Info=True;Connect Timeout={4};";
            var connstr = "";
            if (port == DefaultPort)
                connstr = string.Format(DEF_SQL_CONNECTION, server, dbName, uid,
                    pwd, timeout);
            else
                connstr = string.Format(DEF_SQL_CONNECTION, server + "," + port,
                    dbName, uid, pwd, timeout);
 
            return connstr;
        }
 
        public void Close(DbConnection connection)
        {
            if (connection != null)
            {
                connection.Close();
                connection.Dispose();
            }
        }
 
        public int CommandTimeout
        {
            get
            {
                var defaultTimeOut = 30;
                return DatabaseFactory.CommandTimeOut > 0
                    ? DatabaseFactory.CommandTimeOut
                    : defaultTimeOut;
            }
        }
 
        public string ConnectionString
        {
            get => _ConnectionString;
            set => _ConnectionString = value;
        }
 
        public int ConnectionTimeout
        {
            get
            {
                var defaultTimeOut = 15;
                return DatabaseFactory.ConnectionTimeOut > 0
                    ? DatabaseFactory.ConnectionTimeOut
                    : defaultTimeOut;
            }
        }
 
        public CommandHelper CreateCommand(string commandText)
        {
            return new CommandHelper(this, commandText, CommandType.Text);
        }
 
        public DbCommand CreateCommand(string commandText,
            CommandType commandType)
        {
            return new SqlCommand(commandText)
            {
                CommandText = commandText, CommandType = commandType,
                CommandTimeout = CommandTimeout
            };
        }
 
        public DbCommandBuilder CreateCommandBuilder()
        {
            return new SqlCommandBuilder();
        }
 
        public DbConnection CreateConnection()
        {
            return CreateConnection(_ConnectionString);
        }
 
        public DbConnection CreateConnection(string connectionString)
        {
            DbConnection DBConn = new SqlConnection(connectionString);
            DBConn.Open(); //打开连接
            return DBConn;
        }
 
        public DbDataAdapter CreateDataAdapter()
        {
            return new SqlDataAdapter();
        }
 
        public DbParameter CreateParameter(string parameterName,
            DbType parameterType, int size, string sourceColumn,
            object parameterValue)
        {
            parameterName = ParseParamName(parameterName);
            return new SqlParameter
            {
                ParameterName = parameterName, DbType = parameterType,
                Size = size, SourceColumn = sourceColumn,
                Value = parameterValue, IsNullable = true
            };
        }
 
        public DbParameter CreateParameter(string parameterName,
            object parameterValue)
        {
            parameterName = ParseParamName(parameterName);
            return new SqlParameter
            {
                ParameterName = parameterName, Value = parameterValue,
                IsNullable = true
            };
        }
 
        public CommandHelper CreateSqlProc(string spName)
        {
            return new CommandHelper(this, spName, CommandType.StoredProcedure);
        }
 
        /// <summary>
        ///     创建时间戳参数
        /// </summary>
        /// <param name="parameterName">参数名</param>
        /// <param name="fieldName">字段名</param>
        /// <returns></returns>
        public DbParameter CreateTimestampParameter(string parameterName,
            string fieldName)
        {
            var p = new SqlParameter();
            p.ParameterName = parameterName;
            p.SqlDbType = SqlDbType.Timestamp;
            p.Size = 8;
            p.SourceColumn = fieldName;
            return p;
        }
 
        public DatabaseType DatabaseType => DatabaseType.SqlServer;
 
        public Type DateTimeType => typeof(SqlDateTime);
 
        public int DefaultPort => 1433;
 
        public int ExecuteCommand(DbCommand cmd)
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null && cmd.Transaction == null)
                    cmd.Connection =
                        connection = CreateConnection(_ConnectionString);
 
                return cmd.ExecuteNonQuery();
            }
            finally
            {
                if (connection != null) Close(connection);
            }
        }
 
        public DbDataReader ExecuteReader(string SQL)
        {
            DbCommand cmd = null;
            DbDataReader o = null;
            DbConnection conn = null;
            try
            {
                cmd = new SqlCommand();
                cmd.CommandText = CodeSafeHelper.GetSafeSQL(SQL);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn = CreateConnection(_ConnectionString);
                o = cmd.ExecuteReader();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd != null) cmd.Dispose();
 
                Close(conn);
            }
 
            return o;
        }
 
        public DbDataReader ExecuteReader(DbCommand cmd)
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                return cmd.ExecuteReader();
            }
            finally
            {
                Close(connection);
            }
        }
 
        public T ExecuteReader<T>(DbCommand cmd) where T : new()
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                var obj = default(T);
                using (var dataReader = cmd.ExecuteReader())
                {
                    if (dataReader.Read())
                        obj = DbTools.Convert2Object<T>(dataReader);
                }
 
                return obj;
            }
            finally
            {
                Close(connection);
            }
        }
 
        public T ExecuteReader<T>(string SQL) where T : new()
        {
            DbConnection connection = null;
            DbCommand command = null;
            DbDataReader dataReader = null;
 
            try
            {
                using (connection = CreateConnection())
                {
                    using (command = CreateCommand(SQL, CommandType.Text))
                    {
                        command.Connection = connection;
                        var obj = default(T);
                        using (dataReader = command.ExecuteReader())
                        {
                            if (dataReader.Read())
                                obj = DbTools.Convert2Object<T>(dataReader);
                        }
 
                        return obj;
                    }
                }
            }
            finally
            {
                if (connection != null) connection.Dispose();
 
                if (command != null) command.Dispose();
 
                if (dataReader != null) dataReader.Dispose();
            }
        }
 
        public List<T> ExecuteReader<T>(string SQL,
            Func<DbDataReader, T> action) where T : new()
        {
            DbConnection connection = null;
            DbCommand command = null;
            DbDataReader dataReader = null;
 
            try
            {
                using (connection = CreateConnection())
                {
                    using (command = CreateCommand(SQL, CommandType.Text))
                    {
                        command.Connection = connection;
                        var list = new List<T>();
                        using (dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                                list.Add(action.Invoke(dataReader));
                        }
 
                        return list;
                    }
                }
            }
            finally
            {
                if (connection != null) connection.Dispose();
 
                if (command != null) command.Dispose();
 
                if (dataReader != null) dataReader.Dispose();
            }
        }
 
        public List<T> ExecuteReader<T>(DbCommand cmd,
            Func<DbDataReader, T> action) where T : new()
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                var list = new List<T>();
                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                        list.Add(action.Invoke(dataReader));
                }
 
                return list;
            }
            finally
            {
                Close(connection);
            }
        }
 
        public List<T> ExecuteReaderList<T>(string SQL) where T : new()
        {
            DbConnection connection = null;
            DbCommand command = null;
            DbDataReader dataReader = null;
 
            try
            {
                using (connection = CreateConnection())
                {
                    using (command = CreateCommand(SQL, CommandType.Text))
                    {
                        command.Connection = connection;
                        var list = new List<T>();
                        using (dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                                list.Add(DbTools.Convert2Object<T>(dataReader));
                        }
 
                        return list;
                    }
                }
            }
            finally
            {
                if (connection != null) connection.Dispose();
 
                if (command != null) command.Dispose();
 
                if (dataReader != null) dataReader.Dispose();
            }
        }
 
        public List<T> ExecuteReaderList<T>(DbCommand cmd) where T : new()
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                var list = new List<T>();
                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                        list.Add(DbTools.Convert2Object<T>(dataReader));
                }
 
                return list;
            }
            finally
            {
                Close(connection);
            }
        }
 
        public object ExecuteScalar(string SQL)
        {
            DbConnection connection = null;
            DbCommand cmd = null;
            try
            {
                cmd = CreateCommand(SQL, CommandType.Text);
                cmd.Connection = connection = CreateConnection();
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd != null) cmd.Dispose();
 
                Close(connection);
            }
        }
 
        public object ExecuteScalar(DbCommand cmd)
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                return cmd.ExecuteScalar();
            }
            finally
            {
                Close(connection);
            }
        }
 
        public int ExecuteSQL(string SQL)
        {
            DbConnection connection = null;
            try
            {
                connection = CreateConnection();
                return ExecuteSQL(SQL, connection);
            }
            finally
            {
                Close(connection);
            }
        }
 
 
        /// <summary>
        ///     在事务内提交数据
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="SQL">SQL语句</param>
        /// <returns></returns>
        public int ExecuteTrans(DbTransaction trans, string SQL)
        {
            DbCommand cmd = null;
            var i = -1;
            try
            {
                cmd = new SqlCommand();
                cmd.CommandText = CodeSafeHelper.GetSafeSQL(SQL);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = trans.Connection;
                cmd.Transaction = trans;
 
                i = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd != null) cmd.Dispose();
            }
 
            return i;
        }
 
        public int ExecuteTrans(DbTransaction trans, DbCommand cmd)
        {
            var i = -1;
            try
            {
                cmd.Connection = trans.Connection;
                cmd.Transaction = trans;
                i = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd != null) cmd.Dispose();
            }
 
            return i;
        }
 
        public DataRow GetDataRow(string SQL)
        {
            var dt = GetDataSet(SQL).Tables[0];
            return dt.Rows.Count > 0 ? dt.Rows[0] : null;
        }
 
        public DataSet GetDataSet(DbCommand cmd)
        {
            DbDataAdapter adapter = null;
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection =
                        connection = CreateConnection(_ConnectionString);
 
                var ds = new DataSet();
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);
 
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (adapter != null) adapter.Dispose();
 
                if (cmd != null) cmd.Dispose();
 
                Close(connection);
            }
        }
 
        public DataSet GetDataSet(string SQL)
        {
            DbConnection connection = null;
            try
            {
                connection = CreateConnection(_ConnectionString);
                return GetDataSet(SQL, connection);
            }
            finally
            {
                Close(connection);
            }
        }
 
        /// <summary>
        ///     执行带参数的 Sql 语句或存储过程,并返回 DataSet 对象。
        /// </summary>
        /// <param name="SQL">要执行的 Sql 语句或存储过程名等。</param>
        /// <param name="type">CommandType 参数类型,即该命令是 sql 语句,还是存储过程名等。</param>
        /// <param name="paramlist">参数集合。</param>
        /// <returns>DataSet 对象。</returns>
        public virtual DataSet GetDataSet(string SQL, CommandType type,
            IDataParameter[] paramlist)
        {
            DbCommand cmd = null;
            DbDataAdapter adapter = null;
            DbConnection connection = null;
            try
            {
                cmd = CreateCommand(SQL, type);
                cmd.Connection = connection = CreateConnection();
 
                if (paramlist != null) cmd.Parameters.AddRange(paramlist);
 
                var ds = new DataSet();
                adapter = CreateDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);
 
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (adapter != null) adapter.Dispose();
 
                if (cmd != null) cmd.Dispose();
 
                Close(connection);
            }
        }
 
        /// <summary>
        ///     获取当前表最新(最大)的自增字段值
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public int GetMaxID(string tableName)
        {
            //mssql写法
            var sql = $"select ident_current('{tableName}');";
            var o = ExecuteScalar(sql);
            return o == DBNull.Value || o == null ? 0 : Convert.ToInt32(o);
        }
 
        /// <summary>
        ///     服务器时间
        /// </summary>
        public DateTime GetServerTime()
        {
            var o = ExecuteScalar("SELECT GETDATE() AS SERVER_DATE");
            return Convert.ToDateTime(o);
        }
 
        public List<string> GetStringList(string SQL)
        {
            DbConnection connection = null;
            DbCommand command = null;
            DbDataReader dataReader = null;
 
            try
            {
                using (connection = CreateConnection())
                {
                    using (command = CreateCommand(SQL, CommandType.Text))
                    {
                        command.Connection = connection;
                        var list = new List<string>();
                        using (dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                                list.Add(dataReader.GetValue(0)
                                    .ToString()); //取第1列
                        }
 
                        return list;
                    }
                }
            }
            finally
            {
                if (connection != null) connection.Dispose();
 
                if (command != null) command.Dispose();
 
                if (dataReader != null) dataReader.Dispose();
            }
        }
 
        public List<string> GetStringList(DbCommand cmd)
        {
            DbConnection connection = null;
            try
            {
                if (cmd.Connection == null)
                    cmd.Connection = connection = CreateConnection();
 
                var list = new List<string>();
                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                        list.Add(dataReader.GetValue(0).ToString()); //取第1列
                }
 
                return list;
            }
            finally
            {
                Close(connection);
            }
        }
 
        public DataTable GetTable(string SQL, string tableName = "")
        {
            var dt = GetDataSet(SQL).Tables[0];
            if (tableName != "") dt.TableName = tableName;
 
            return dt;
        }
 
        public DataTable GetTable(DbCommand cmd, string tableName = "")
        {
            var dt = GetDataSet(cmd).Tables[0];
            if (tableName != "") dt.TableName = tableName;
 
            return dt;
        }
 
        public DataTable GetTop(int top, string tableName, string fields = "",
            List<DbParameter> where = null,
            string orderBy = "")
        {
            var cmd = CreateCommand("");
 
            fields = string.IsNullOrWhiteSpace(fields) ? "*" : fields;
            orderBy = string.IsNullOrEmpty(orderBy)
                ? ""
                : " ORDER BY " + orderBy;
 
            var whereSQL = "";
            if (where != null && where.Count > 0)
            {
                string pName;
                foreach (var p in where)
                {
                    pName = p.ParameterName;
 
                    if (pName.IndexOf(ParamSymboName) >= 0) //参数名称带有符号,如:@Code
                        whereSQL = whereSQL +
                                   $" AND {pName.Replace(ParamSymboName, "")}={p.ParameterName}";
                    else
                        whereSQL = whereSQL +
                                   $" AND {p.ParameterName}={ParamSymboName + p.ParameterName}";
 
                    cmd.Command.Parameters.Add(p);
                }
            }
 
            whereSQL = string.IsNullOrEmpty(whereSQL)
                ? ""
                : " WHERE 1=1 " + whereSQL;
 
            var SQL =
                $"SELECT TOP {top} {fields} FROM {tableName} {whereSQL} {orderBy};";
 
            cmd.Command.CommandText = CodeSafeHelper.GetSafeSQL(SQL);
            return GetTable(cmd.Command, tableName);
        }
 
        public DataTable meta_GetDatabase()
        {
            var sql =
                "SELECT Name AS DBName,filename AS FilePath,crdate AS CreationTime,Version FROM Master..SysDatabases";
            return GetTable(sql, "SysDatabases");
        }
 
        public List<MetaDBNames> meta_GetDatabaseList()
        {
            var sql =
                "SELECT Name AS DBName,filename AS FilePath,crdate AS CreationTime,Version FROM Master..SysDatabases";
            return ExecuteReaderList<MetaDBNames>(sql);
        }
 
        public List<MetaStoreProcedure> meta_GetStoreProcList(
            string dbName = "")
        {
            var sql =
                "SELECT type,name FROM sys.sql_modules inner join sysobjects  on sys.sql_modules.object_id = sysobjects.id  and type in ('p','fn') and category=0";
 
            CodeSafeHelper.IsCheckSQM = false;
            var result = new List<MetaStoreProcedure>();
            var sp = CreateCommand(sql);
            var dt = GetTable(sp.Command);
            foreach (DataRow R in dt.Rows)
            {
                if (R["type"].ToString().Trim().ToUpper() == "P")
                    result.Add(new MetaStoreProcedure
                    {
                        Type = MetaStoreProcedureType.StoreProcedure,
                        Name = R["name"].ToString()
                    });
 
                if (R["type"].ToString().Trim().ToUpper() == "FN")
                    result.Add(new MetaStoreProcedure
                    {
                        Type = MetaStoreProcedureType.Function,
                        Name = R["name"].ToString()
                    });
            }
 
            return result;
        }
 
        public DataTable meta_GetTableNames(string dbName = "")
        {
            return GetTable(meta_GetTablesNamesSQL());
        }
 
        public List<MetaTableNames> meta_GetTableNamesList(string dbName = "")
        {
            return ExecuteReaderList<MetaTableNames>(meta_GetTablesNamesSQL());
        }
 
        public DataTable meta_GetTableStru(string tableName)
        {
            var b = CodeSafeHelper.IsCheckSQM;
            try
            {
                CodeSafeHelper.IsCheckSQM = false;
                var sp = CreateCommand(meta_GetTableStruSQL());
                sp.AddParam("TableName", tableName);
                return GetTable(sp.Command, tableName);
            }
            finally
            {
                CodeSafeHelper.IsCheckSQM = b;
            }
        }
 
        public List<MetaTableStructure> meta_GetTableStruList(string tableName)
        {
            var b = CodeSafeHelper.IsCheckSQM;
            try
            {
                CodeSafeHelper.IsCheckSQM = false;
                var sp = CreateCommand(meta_GetTableStruSQL());
                sp.AddParam("TableName", tableName);
                return ExecuteReaderList<MetaTableStructure>(sp.Command);
            }
            finally
            {
                CodeSafeHelper.IsCheckSQM = b;
            }
        }
 
        /// <summary>
        ///     参数符号.如: WHERE Code=@Code
        /// </summary>
        public string ParamSymboName { get; set; } = "@";
 
        /// <summary>
        ///     返回包含参数符号的参数名称,比如:@Code, :Code, ?p_Code
        /// </summary>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public string ParseParamName(string paramName)
        {
            if (string.IsNullOrEmpty(ParamSymboName) ||
                string.IsNullOrEmpty(paramName)) return paramName;
 
            if (paramName.IndexOf(ParamSymboName) == 0) //首字母包含
                return paramName;
 
            return ParamSymboName + paramName; //添加参数符号
        }
 
        public DbType ToDbType(string sourceType)
        {
            return DBDataTypes.GetDbTypeByMsSqlType(sourceType);
        }
 
        public Type ToNetType(string sourceType)
        {
            return DBDataTypes.GetNetTypeByMsSql(sourceType);
        }
 
        public DbTransaction TransBegin()
        {
            return CreateConnection().BeginTransaction();
        }
 
        public void TransCommit(DbTransaction trans,
            bool closeConnection = false)
        {
            trans.Commit();
            if (closeConnection) Close(trans.Connection);
        }
 
        public void TransRollback(DbTransaction trans,
            bool closeConnection = false)
        {
            trans.Rollback();
            if (closeConnection) Close(trans.Connection);
        }
 
        public bool UpdateDataSet(DataTable ds, string tableName, string KEY)
        {
            //先删除原表数据
            var sql = "";
            var ErrorMsg = "";
            foreach (DataRow dr in ds.Rows)
            {
                sql = string.Format(@"delete from {0} where {1} in ('{2}')",
                    tableName, KEY, dr[KEY]);
                break;
            }
 
            var a = ExecuteSQL(sql);
            var colMapping = new SqlBulkCopyColumnMapping[ds.Columns.Count];
            for (var i = 0; i < ds.Columns.Count; i++)
                colMapping[i] =
                    new SqlBulkCopyColumnMapping(ds.Columns[i].ColumnName,
                        ds.Columns[i].ColumnName);
 
            DataTableToSQLServer(ds, _ConnectionString, tableName, colMapping,
                ref ErrorMsg);
            return true;
        }
 
 
        public bool InstDataSet(DataTable ds, string tableName)
        {
            //先删除原表数据
            var ErrorMsg = "";
            var colMapping = new SqlBulkCopyColumnMapping[ds.Columns.Count];
            for (var i = 0; i < ds.Columns.Count; i++)
                colMapping[i] =
                    new SqlBulkCopyColumnMapping(ds.Columns[i].ColumnName,
                        ds.Columns[i].ColumnName);
 
            DataTableToSQLServer(ds, _ConnectionString, tableName, colMapping,
                ref ErrorMsg);
            return true;
        }
 
        public int ExecuteSQLT(string conn, string sql, object FingerDataTwo,
            object Report)
        {
            DbConnection connection = null;
            try
            {
                var ConnectString = conn;
 
                //string sql = "update SYS_Reports set Data = @FingerDataTwo WHERE ReportTitle= @UserId";
                var con = new SqlConnection(ConnectString);
                var cmd = new SqlCommand(sql, con);
                cmd.Parameters.Add("@FingerDataTwo", SqlDbType.VarBinary)
                    .Value = FingerDataTwo;
                cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = Report;
                con.Open();
                var i = cmd.ExecuteNonQuery();
                con.Close();
 
                return 1;
            }
            finally
            {
                Close(connection);
            }
        }
 
        //2022-05-01 liu
        public bool AddTable(DataTable dt, string tableName)
        {
            using (var sqlCon = new SqlConnection(_ConnectionString))
            {
                try
                {
                    sqlCon.Open();
                    using (var bulkCopy = new SqlBulkCopy(sqlCon))
                    {
                        bulkCopy.DestinationTableName = tableName;
                        for (var i = 0; i < dt.Columns.Count; i++)
                            bulkCopy.ColumnMappings.Add(dt.Columns[i].Caption,
                                dt.Columns[i].Caption);
 
                        bulkCopy.WriteToServer(dt);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sqlCon.Close();
                }
            }
        }
 
        #region 封装批量插入数据SQL Server数据的方法
 
        /// <summary>
        ///     封装批量插入数据SQL Server数据的方法
        /// </summary>
        /// <param name="dt">源数据表</param>
        /// <param name="connectString">数据库连接字符串</param>
        /// <param name="tableName">目标表名</param>
        /// <param name="colMapping">字段映射</param>
        public bool DataTableToSQLServer(DataTable dt, string connectString,
            string tableName,
            SqlBulkCopyColumnMapping[] colMapping, ref string msg)
        {
            using (var destinationConnection = new SqlConnection(connectString))
            {
                destinationConnection.Open();
 
                using (var bulkCopy = new SqlBulkCopy(destinationConnection,
                           SqlBulkCopyOptions.FireTriggers, null))
                {
                    try
                    {
                        bulkCopy.DestinationTableName = tableName; //要插入的表的表名
                        bulkCopy.BatchSize = dt.Rows.Count;
                        foreach (var item in colMapping)
                            bulkCopy.ColumnMappings.Add(item);
 
                        bulkCopy.WriteToServer(dt);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        msg = "[" + tableName + "]" + ex.Message;
                        return false;
                    }
                }
            }
        }
 
        #endregion
 
        public bool DeleteDataSet(DataTable ds, string tableName, string KEY)
        {
            var sql = "";
            var ErrorMsg = "";
            foreach (DataRow dr in ds.Rows)
            {
                sql = string.Format(@"delete from {0} where {1} in ('{2}')",
                    tableName, KEY, dr[KEY]);
                break;
            }
 
            try
            {
                var a = ExecuteSQL(sql);
                if (a > 0) return true;
            }
            catch (Exception)
            {
                return false;
            }
 
            return false;
        }
 
        public int ExecuteSQL(string SQL, DbConnection conn)
        {
            DbCommand cmd = null;
            var i = -1;
            try
            {
                cmd = new SqlCommand();
                cmd.CommandText = CodeSafeHelper.GetSafeSQL(SQL);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;
                i = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd != null) cmd.Dispose();
            }
 
            return i;
        }
 
        public DataSet GetDataSet(string SQL, DbConnection conn)
        {
            DbCommand cmd = null;
            DbDataAdapter adapter = null;
            try
            {
                cmd = new SqlCommand();
                cmd.CommandText = CodeSafeHelper.GetSafeSQL(SQL);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;
 
                var ds = new DataSet();
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (adapter != null) adapter.Dispose();
 
                if (cmd != null) cmd.Dispose();
            }
        }
 
        private DbCommand meta_GetTablesNamesSQL()
        {
            var cmd =
                CreateCommand(
                    "select id,type,name from sysobjects where type in(@U,@V) order by name");
            cmd.AddParam("@U", "U");
            cmd.AddParam("@V", "V");
            return cmd.Command;
        }
 
        private string meta_GetTableStruSQL()
        {
            var sql = new StringBuilder();
            sql.AppendLine("SELECT ");
            sql.AppendLine("        TableName=d.name,    ");
            sql.AppendLine("        FieldOrder=a.colorder,");
            sql.AppendLine("        FieldName=a.name,");
            sql.AppendLine(
                "        IsIdentity=CASE WHEN COLUMNPROPERTY(a.id,a.name, 'IsIdentity')=1 THEN 'Y' ELSE 'N' END,");
            sql.AppendLine(
                "        PK=CASE WHEN EXISTS(SELECT 1 FROM sysobjects WHERE xtype= 'PK' AND parent_obj=a.id AND name IN (");
            sql.AppendLine(
                "            SELECT name   FROM   sysindexes   WHERE   indid IN(");
            sql.AppendLine(
                "            SELECT indid   FROM   sysindexkeys   WHERE   id   =   a.id   AND   colid=a.colid))) THEN 'Y' ELSE 'N' END,");
            sql.AppendLine(
                "        FK=CASE WHEN EXISTS(SELECT 1 FROM sysobjects WHERE xtype= 'F' AND parent_obj=a.id AND name IN (");
            sql.AppendLine(
                "            SELECT name   FROM   sysindexes   WHERE   indid IN(");
            sql.AppendLine(
                "            SELECT indid   FROM   sysindexkeys   WHERE   id   =   a.id   AND   colid=a.colid))) THEN 'Y' ELSE 'N' END,");
            sql.AppendLine("        IDX=CASE WHEN EXISTS(        ");
            sql.AppendLine(
                "            SELECT TOP 1 dd.name FROM sysindexes aa JOIN sysindexkeys bb ON aa.id = bb.id  AND aa.indid = bb.indid");
            sql.AppendLine("            JOIN sysobjects cc ON bb.id = cc.id");
            sql.AppendLine(
                "            JOIN syscolumns dd ON bb.id = dd.id  AND bb.colid = dd.colid");
            sql.AppendLine(
                "            WHERE dd.name=a.name AND dd.id=a.id AND cc.id=d.id     AND aa.indid NOT IN ( 0 , 255 ) ) THEN 'Y' ELSE 'N' END,");
            sql.AppendLine("        FieldType=b.name,");
            sql.AppendLine("        FieldLength=a.length,");
            sql.AppendLine("        Prec=COLUMNPROPERTY(a.id,a.name, 'PRECISION '),");
            sql.AppendLine(
                "        Scale=isnull(COLUMNPROPERTY(a.id,a.name, 'Scale '),0),");
            sql.AppendLine(
                "        AllowNull=CASE WHEN a.isnullable=1 THEN 'Y' ELSE 'N' END,");
            sql.AppendLine("        DefaultValue=isnull(e.text, ' '),");
            sql.AppendLine(
                "        FieldCaption=CASE WHEN ISNULL(g.[value], '')='' THEN a.name ELSE g.[value] END");
            sql.AppendLine("        FROM syscolumns a");
            sql.AppendLine(
                "        LEFT JOIN systypes   b   on   a.xusertype=b.xusertype");
            sql.AppendLine(
                "        INNER JOIN sysobjects   d   on   a.id=d.id     and   d.xtype IN ('U','V')   and     d.name <> 'dtproperties'");
            sql.AppendLine(
                "        LEFT JOIN syscomments   e   on   a.cdefault=e.id");
            sql.AppendLine(
                "        LEFT JOIN sys.extended_properties   g ON a.id=g.major_id   and   a.colid=g.minor_id  "); //  --sql2005 改为 sysproperties表
            sql.AppendLine(
                "        WHERE d.name= @TableName         "); //--如果只查询指定表,加上此条件
 
            return sql.ToString();
        }
 
 
        #region
 
        protected AdapterRowUpdatingEvent _MyRowUpdatingEvent;
 
        public DbDataAdapter CreateDataAdapter(
            AdapterRowUpdatingEvent eventHandler)
        {
            _MyRowUpdatingEvent = eventHandler;
 
            var adp = new SqlDataAdapter();
            adp.RowUpdating += Adp_RowUpdating;
 
            return adp;
        }
 
        private void Adp_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {
            if (_MyRowUpdatingEvent != null) _MyRowUpdatingEvent(sender, e);
        }
 
        #endregion
    }
}