forked from cyq1162/cyqdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DalBase.cs
1346 lines (1286 loc) · 47 KB
/
DalBase.cs
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
using System;
using System.Data.Common;
using System.Data;
using System.Diagnostics;
using CYQ.Data.SQL;
using System.Collections.Generic;
using CYQ.Data.Tool;
using System.Data.SqlTypes;
using System.Threading;
namespace CYQ.Data
{
/// <summary>
/// 数据库操作基类 (模板模式:Template Method)
/// 属性管理
/// </summary>
internal abstract partial class DalBase : IDisposable
{
#region 对外公开的属性
/// <summary>
/// 记录SQL语句信息
/// </summary>
public System.Text.StringBuilder DebugInfo = new System.Text.StringBuilder();
/// <summary>
/// 执行命令时所受影响的行数(-2为发生异常)。
/// </summary>
public int RecordsAffected = 0;
/// <summary>
/// 当前是否开启事务
/// </summary>
public bool IsOpenTrans = false;
/// <summary>
/// 原生态传进来的配置名(或链接)
/// </summary>
public string ConnName
{
get
{
return !ConnObj.Master.IsBackup ? ConnObj.Master.ConnName : ConnObj.BackUp.ConnName;
}
}
/// <summary>
/// 数据库主从备链接管理对象;
/// </summary>
public ConnObject ConnObj;
/// <summary>
/// 当前使用中的链接对象
/// </summary>
public ConnBean UsingConnBean;
/// <summary>
/// 获得链接的数据库名称
/// </summary>
public virtual string DataBase
{
get
{
if (!string.IsNullOrEmpty(_con.Database))
{
return _con.Database;
}
else if (DataBaseType == DalType.Oracle)
{
// (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT = 1521)))(CONNECT_DATA =(Sid = Aries)))
int i = _con.DataSource.LastIndexOf('=') + 1;
return _con.DataSource.Substring(i).Trim(' ', ')');
}
else
{
return System.IO.Path.GetFileNameWithoutExtension(_con.DataSource);
}
}
}
private static MDictionary<string, string> _VersionCache = new MDictionary<string, string>();
private string _Version = string.Empty;
/// <summary>
/// 数据库的版本号
/// </summary>
public string Version
{
get
{
if (string.IsNullOrEmpty(_Version))
{
switch (DataBaseType)
{
case DalType.Txt:
_Version = "txt2.0";
break;
case DalType.Xml:
_Version = "xml2.0";
break;
default:
if (_VersionCache.ContainsKey(ConnName))
{
_Version = _VersionCache[ConnName];
}
else
{
if (IsOpenTrans && UsingConnBean.IsSlave)// && 事务操作时,如果在从库,切回主库
{
ResetConn(ConnObj.Master);
}
if (OpenCon(UsingConnBean, AllowConnLevel.MaterBackupSlave))//这里可能切换链接
{
_Version = _con.ServerVersion;
if (!_VersionCache.ContainsKey(ConnName))
{
_VersionCache.Set(ConnName, _Version);
}
if (!IsOpenTrans)//避免把事务给关闭了。
{
CloseCon();
}
}
}
break;
}
}
return _Version;
}
}
/// <summary>
/// 当前操作的数据库类型
/// </summary>
public DalType DataBaseType
{
get
{
return ConnObj.Master.ConnDalType;
}
}
#endregion
/// <summary>
/// 是否允许进入写日志中模块(默认true)
/// </summary>
public bool IsWriteLogOnError = true;
protected bool isUseUnsafeModeOnSqlite = false;
private bool isAllowResetConn = true;//如果执行了非查询之后,为了数据的一致性,不允许切换到Slave数据库链接
private string tempSql = string.Empty;//附加信息,包括调试信息
private IsolationLevel _TranLevel = IsolationLevel.ReadCommitted;
internal IsolationLevel TranLevel
{
get
{
if (_tran != null && _com != null && _com.Transaction != null)
{
return _com.Transaction.IsolationLevel;
}
return _TranLevel;
}
set
{
if (_tran != null && _com != null && _com.Transaction != null)
{
Error.Throw("IsolationLevel is readonly when transaction is begining!");
}
else
{
_TranLevel = value;
}
}
}
protected DbProviderFactory _fac = null;
protected DbConnection _con = null;
protected DbCommand _com;
internal DbTransaction _tran;
private Stopwatch _watch;
public DbConnection Con
{
get
{
return _con;
}
}
public DbCommand Com
{
get
{
return _com;
}
}
private bool _IsRecordDebugInfo = true;
/// <summary>
/// 是否允许记录SQL语句 (内部操作会关掉此值为False)
/// </summary>
public bool IsRecordDebugInfo
{
get
{
return (AppConfig.Debug.OpenDebugInfo || AppConfig.Debug.SqlFilter > -1) && _IsRecordDebugInfo;
}
set
{
_IsRecordDebugInfo = value;
}
}
public DalBase(ConnObject co)
{
this.ConnObj = co;
this.UsingConnBean = co.Master;
_fac = GetFactory();
_con = _fac.CreateConnection();
try
{
_con.ConnectionString = co.Master.ConnString;
}
catch (Exception err)
{
Error.Throw("check the connectionstring is be ok!" + AppConst.BR + "error:" + err.Message + AppConst.BR + ConnName);
}
_com = _con.CreateCommand();
if (_com != null)//Txt| Xml 时返回Null
{
_com.Connection = _con;
_com.CommandTimeout = AppConfig.DB.CommandTimeout;
}
if (IsRecordDebugInfo)//开启秒表计算
{
_watch = new Stopwatch();
}
//if (AppConfig.DB.LockOnDbExe && dalType == DalType.Access)
//{
// string dbName = DataBase;
// if (!_dbOperator.ContainsKey(dbName))
// {
// try
// {
// _dbOperator.Add(dbName, false);
// }
// catch
// {
// }
// }
//}
//_com.CommandTimeout = 1;
}
protected abstract DbProviderFactory GetFactory();
#region 拿表、视图、存储过程等元数据。
public virtual Dictionary<string, string> GetTables()
{
return GetSchemaDic(GetSchemaSql("U"));
}
public virtual Dictionary<string, string> GetViews()
{
return GetSchemaDic(GetSchemaSql("V"));
}
public virtual Dictionary<string, string> GetProcs()
{
return GetSchemaDic(GetSchemaSql("P"));
}
protected Dictionary<string, string> GetSchemaDic(string sql)
{
if (string.IsNullOrEmpty(sql))
{
return null;
}
Dictionary<string, string> dic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DbDataReader sdr = ExeDataReader(sql, false);
if (sdr != null)
{
string tableName = string.Empty;
while (sdr.Read())
{
tableName = Convert.ToString(sdr["TableName"]);
if (!dic.ContainsKey(tableName))
{
dic.Add(tableName, Convert.ToString(sdr["Description"]));
}
}
sdr.Close();
sdr = null;
}
return dic;
}
protected virtual string GetSchemaSql(string type)
{
return "";
}
#endregion
#region 数据库链接切换相关逻辑
/// <summary>
/// 切换数据库(修改数据库链接)
/// </summary>
internal DBResetResult ChangeDatabase(string dbName)
{
if (_con.State == ConnectionState.Closed)//事务中。。不允许切换
{
try
{
if (IsExistsDbNameWithCache(dbName))//新的数据库不存在。。不允许切换
{
string newConnString = GetConnString(dbName);
_con.ConnectionString = newConnString;
ConnObj = ConnObject.Create(dbName + "Conn");
ConnObj.Master.ConnName = dbName + "Conn";
ConnObj.Master.ConnString = newConnString;
return DBResetResult.Yes;
}
else
{
return DBResetResult.No_DBNoExists;
}
}
catch (Exception err)
{
Log.Write(err, LogType.DataBase);
}
}
return DBResetResult.No_Transationing;
}
//检测并切换数据库链接。
internal DBResetResult ChangeDatabaseWithCheck(string dbTableName)//----------
{
if (IsOwnerOtherDb(dbTableName))//数据库名称变化了。
{
string dbName = dbTableName.Split('.')[0];
return ChangeDatabase(dbName);
}
return DBResetResult.No_SaveDbName;
}
internal DalBase ResetDalBase(string dbTableName)
{
if (IsOwnerOtherDb(dbTableName))//是其它数据库名称。
{
if (_con.State != ConnectionState.Closed)//事务中。。创建新链接切换
{
string dbName = dbTableName.Split('.')[0];
return DalCreate.CreateDal(GetConnString(dbName));
}
}
return this;
}
/// <summary>
/// 是否数据库名称变化了
/// </summary>
/// <param name="dbTableName"></param>
/// <returns></returns>
private bool IsOwnerOtherDb(string dbTableName)
{
int index = dbTableName.IndexOf('.');//DBName.TableName
if (index > 0 && !dbTableName.Contains(" ")) //排除视图语句
{
string dbName = dbTableName.Split('.')[0];
if (string.Compare(DataBase, dbName, StringComparison.OrdinalIgnoreCase) != 0 && ConnName.IndexOf(DataBase) == ConnName.LastIndexOf(DataBase))
{
return true;
}
}
return false;
}
protected string GetConnString(string dbName)
{
string newConn = AppConfig.GetConn(dbName + "Conn");
if (!string.IsNullOrEmpty(newConn))
{
return ConnBean.Create(newConn).ConnString;
}
return UsingConnBean.ConnString.Replace(DataBase, dbName);
}
static MDictionary<string, bool> dbList = new MDictionary<string, bool>(3);
private bool IsExistsDbNameWithCache(string dbName)
{
try
{
string key = DataBaseType.ToString() + "." + dbName;
if (dbList.ContainsKey(key))
{
return dbList[key];
}
bool result = IsExistsDbName(dbName);
dbList.Add(key, result);
return result;
}
catch
{
return true;
}
}
protected abstract bool IsExistsDbName(string dbName);
#endregion
private int returnValue = -1;
/// <summary>
/// 存储过程返回值。
/// </summary>
public int ReturnValue
{
get
{
if (returnValue == -1 && _com != null && _com.Parameters != null && _com.Parameters.Count > 0)
{
for (int i = _com.Parameters.Count - 1; i >= 0; i--)
{
if (_com.Parameters[i].Direction == ParameterDirection.ReturnValue)
{
int.TryParse(Convert.ToString(_com.Parameters[i].Value), out returnValue);
break;
}
}
}
return returnValue;
}
set
{
returnValue = value;
}
}
/// <summary>
/// 存储过程OutPut输出参数值。
/// 如果只有一个输出,则为值;
/// 如果有多个输出,则为Dictionary。
/// </summary>
public object OutPutValue
{
get
{
if (_com != null && _com.Parameters != null && _com.Parameters.Count > 0)
{
Dictionary<string, object> opValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
object outPutValue = null;
foreach (DbParameter para in _com.Parameters)
{
if (para.Direction == ParameterDirection.Output)
{
opValues.Add(para.ParameterName, para.Value);
outPutValue = para.Value;
}
}
if (opValues.Count < 2)
{
opValues = null;
return outPutValue;
}
return opValues;
}
return null;
}
}
public virtual char Pre
{
get
{
return '@';
}
}
#region 参数化管理
public bool AddParameters(string parameterName, object value)
{
return AddParameters(parameterName, value, DbType.String, -1, ParameterDirection.Input);
}
public virtual bool AddParameters(string parameterName, object value, DbType dbType, int size, ParameterDirection direction)
{
if (DataBaseType == DalType.Oracle)
{
parameterName = parameterName.Replace(":", "").Replace("@", "");
if (dbType == DbType.String && size > 4000)
{
AddCustomePara(parameterName, size == int.MaxValue ? ParaType.CLOB : ParaType.NCLOB, value, null);
return true;
}
}
else
{
parameterName = parameterName.Substring(0, 1) == Pre.ToString() ? parameterName : Pre + parameterName;
}
if (Com.Parameters.Contains(parameterName))//已经存在,不添加
{
return false;
}
DbParameter para = _fac.CreateParameter();
para.ParameterName = parameterName;
para.Value = value == null ? DBNull.Value : value;
if (dbType == DbType.Time)// && dalType != DalType.MySql
{
para.DbType = DbType.String;
}
else
{
if (dbType == DbType.DateTime && value != null)
{
string time = Convert.ToString(value);
if (DataBaseType == DalType.MsSql && time == DateTime.MinValue.ToString())
{
para.Value = SqlDateTime.MinValue;
}
else if (DataBaseType == DalType.MySql && (time == SqlDateTime.MinValue.ToString() || time == DateTime.MinValue.ToString()))
{
para.Value = DateTime.MinValue;
}
}
para.DbType = dbType;
}
if (dbType == DbType.Binary && DataBaseType == DalType.MySql)//(mysql不能设定长度,否则会报索引超出了数组界限错误【已过时,旧版本的MySql.Data.dll不能指定长度】)。
{
if (value != null)
{
byte[] bytes = value as byte[];
para.Size = bytes.Length;//新版本的MySql.Data.dll 修正了长度指定(不指定就没数据进去),所以又要指定长度,Shit
}
else
{
para.Size = -1;
}
}
else if (dbType != DbType.Binary && size > -1)
{
if (size != para.Size)
{
para.Size = size;
}
}
para.Direction = direction;
Com.Parameters.Add(para);
return true;
}
internal virtual void AddCustomePara(string paraName, ParaType paraType, object value, string typeName)
{
switch (paraType)
{
case ParaType.OutPut:
AddParameters(paraName, null, DbType.String, 2000, ParameterDirection.Output);
break;
case ParaType.InputOutput:
AddParameters(paraName, null, DbType.String, 2000, ParameterDirection.InputOutput);
break;
case ParaType.ReturnValue:
AddParameters(paraName, null, DbType.Int32, 32, ParameterDirection.ReturnValue);
break;
}
}
//internal virtual void AddCustomePara(string paraName, ParaType paraType, object value)
//{
//}
//public abstract DbParameter GetNewParameter();
public void ClearParameters()
{
if (_com != null && _com.Parameters != null)
{
_com.Parameters.Clear();
}
}
/// <summary>
/// 处理内置的MSSQL和Oracle两种存储过程分页
/// </summary>
protected virtual void AddReturnPara() { }
private void SetCommandText(string commandText, bool isProc)
{
if (OracleDal.clientType > 0)
{
Type t = _com.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty("BindByName");
if (pi != null)
{
pi.SetValue(_com, true, null);
}
}
_com.CommandText = isProc ? commandText : SqlFormat.Compatible(commandText, DataBaseType, false);
if (!isProc && DataBaseType == DalType.SQLite && _com.CommandText.Contains("charindex"))
{
_com.CommandText += " COLLATE NOCASE";//忽略大小写
}
//else if (isProc && dalType == DalType.MySql)
//{
// _com.CommandText = "Call " + _com.CommandText;
//}
_com.CommandType = isProc ? CommandType.StoredProcedure : CommandType.Text;
//if (isProc)
//{
// if (commandText.Contains("SelectBase") && !_com.Parameters.Contains("ReturnValue"))
// {
// AddReturnPara();
// //检测是否存在分页存储过程,若不存在,则创建。
// Tool.DBTool.CreateSelectBaseProc(DataBaseType, ConnName);//内部分检测是否已创建过。
// }
//}
//else
//{
//取消多余的参数,新加的小贴心,过滤掉用户不小心写多的参数。
if (_com != null && _com.Parameters != null && _com.Parameters.Count > 0)
{
bool needToReplace = (DataBaseType == DalType.Oracle || DataBaseType == DalType.MySql) && _com.CommandText.Contains("@");
string paraName;
for (int i = 0; i < _com.Parameters.Count; i++)
{
paraName = _com.Parameters[i].ParameterName.TrimStart(Pre);//默认自带前缀的,取消再判断
if (needToReplace && _com.CommandText.IndexOf("@" + paraName) > -1)
{
//兼容多数据库的参数(虽然提供了=:?"为兼容语法,但还是贴心的再处理一下)
switch (DataBaseType)
{
case DalType.Oracle:
case DalType.MySql:
_com.CommandText = _com.CommandText.Replace("@" + paraName, Pre + paraName);
break;
}
}
if (_com.CommandText.IndexOf(Pre + paraName, StringComparison.OrdinalIgnoreCase) == -1)
{
_com.Parameters.RemoveAt(i);
i--;
}
}
}
// }
//else
//{
// string checkText = commandText.ToLower();
// //int index=
// //if (checkText.IndexOf("table") > -1 && (checkText.IndexOf("delete") > -1 || checkText.IndexOf("drop") > -1 || checkText.IndexOf("truncate") > -1))
// //{
// // Log.WriteLog(commandText);
// //}
//}
if (IsRecordDebugInfo)
{
tempSql = GetParaInfo(_com.CommandText) + AppConst.BR + "execute time is: ";
}
}
#endregion
#region 调试信息管理
private string GetParaInfo(string commandText)
{
string paraInfo = DataBaseType + "." + DataBase + ".SQL: " + AppConst.BR + commandText;
foreach (DbParameter item in _com.Parameters)
{
paraInfo += AppConst.BR + "Para: " + item.ParameterName + "-> " + (item.Value == DBNull.Value ? "DBNull.Value" : item.Value);
}
return paraInfo;
}
/// <summary>
/// 记录执行时间
/// </summary>
private void WriteTime()
{
if (IsRecordDebugInfo && _watch != null)
{
_watch.Stop();
double ms = _watch.Elapsed.TotalMilliseconds;
tempSql += ms + " (ms)" + AppConst.HR;
if (AppConfig.Debug.OpenDebugInfo)
{
DebugInfo.Append(tempSql);
if (AppDebug.IsRecording && ms >= AppConfig.Debug.InfoFilter)
{
AppDebug.Add(tempSql);
}
}
if (AppConfig.Debug.SqlFilter >= 0 && ms >= AppConfig.Debug.SqlFilter)
{
Log.Write(tempSql, LogType.Debug);
}
_watch.Reset();
tempSql = null;
}
}
#endregion
#region 事务管理
public bool EndTransaction()
{
IsOpenTrans = false;
if (_tran != null)
{
try
{
if (_tran.Connection == null)
{
return false;//上一个执行语句发生了异常(特殊情况在ExeReader guid='xxx' 但不抛异常)
}
_tran.Commit();
}
catch (Exception err)
{
RollBack();
WriteError("EndTransaction():" + err.Message);
return false;
}
finally
{
_tran = null;
CloseCon();
}
}
return true;
}
/// <summary>
/// 事务(有则)回滚
/// </summary>
/// <returns></returns>
public bool RollBack()
{
if (_tran != null)
{
try
{
if (_tran.Connection != null)
{
_tran.Rollback();
}
}
catch (Exception)
{
return false;
}
finally
{
_tran = null;//以便重启事务,避免无法二次回滚。
}
}
return true;
}
#endregion
#region 异常处理
internal delegate void OnException(string msg);
internal event OnException OnExceptionEvent;
internal bool IsOnExceptionEventNull
{
get
{
return OnExceptionEvent == null;
}
}
/// <summary>
/// 输出错误(若事务中,回滚事务)
/// </summary>
/// <param name="err"></param>
internal void WriteError(string err)
{
err = DataBaseType + " Call Function::" + err;
if (_watch != null && _watch.IsRunning)
{
_watch.Stop();
_watch.Reset();
}
RollBack();
if (IsWriteLogOnError)
{
Log.Write(err + AppConst.BR + DebugInfo, LogType.DataBase);
}
if (OnExceptionEvent != null)
{
try
{
OnExceptionEvent(err);
}
catch
{
}
}
if (IsOpenTrans)
{
Dispose();//事务中发生语句语法错误,直接关掉资源,避免因后续代码继续执行。
}
}
#endregion
public void Dispose()
{
if (_con != null)
{
CloseCon();
_con = null;
}
if (_com != null)
{
_com = null;
}
if (_watch != null)
{
_watch = null;
}
}
}
/// <summary>
/// 执行管理
/// </summary>
internal abstract partial class DalBase
{
private DbDataReader ExeDataReaderSQL(string cmdText, bool isProc)
{
DbDataReader sdr = null;
ConnBean coSlave = null;
if (!IsOpenTrans)// && _IsAllowRecordSql
{
coSlave = ConnObj.GetSlave();
}
else if (UsingConnBean.IsSlave)// && 事务操作时,如果在从库,切回主库
{
ResetConn(ConnObj.Master);
}
if (OpenCon(coSlave, AllowConnLevel.MaterBackupSlave))
{
try
{
CommandBehavior cb = CommandBehavior.CloseConnection;
if (_IsRecordDebugInfo)//外部SQL,带表结构返回
{
cb = IsOpenTrans ? CommandBehavior.KeyInfo : CommandBehavior.CloseConnection | CommandBehavior.KeyInfo;
}
else if (IsOpenTrans)
{
cb = CommandBehavior.Default;//避免事务时第一次拿表结构链接被关闭。
}
sdr = _com.ExecuteReader(cb);
if (sdr != null)
{
RecordsAffected = sdr.RecordsAffected;
}
}
catch (DbException err)
{
string msg = "ExeDataReader():" + err.Message;
DebugInfo.Append(msg + AppConst.BR);
RecordsAffected = -2;
WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText)));
}
//finally
//{
// if (coSlave != null)
// {
// ChangeConn(connObject.Master);//恢复链接。
// }
//}
}
return sdr;
}
public DbDataReader ExeDataReader(string cmdText, bool isProc)
{
SetCommandText(cmdText, isProc);
DbDataReader sdr = null;
//if (_dbOperator.ContainsKey(DataBase))
//{
// if (!CheckIsConcurrent())
// {
// // dbOperator[DataBase] = true;
// sdr = ExeDataReaderSQL(cmdText, isProc);
// // dbOperator[DataBase] = false;
// }
//}
//else
//{
sdr = ExeDataReaderSQL(cmdText, isProc);
//}
WriteTime();
return sdr;
}
private int ExeNonQuerySQL(string cmdText, bool isProc)
{
RecordsAffected = -2;
if (IsOpenTrans && UsingConnBean.IsSlave)// && 事务操作时,如果在从库,切回主库
{
ResetConn(ConnObj.Master);
}
if (OpenCon())//这里也会切库了,同时设置了10秒切到主库。
{
try
{
if (UsingConnBean.ConnString != ConnObj.Master.ConnString)
{
// recordsAffected = -2;//从库不允许执行非查询操作。
string msg = "You can't do ExeNonQuerySQL() on Slave DataBase!";
DebugInfo.Append(msg + AppConst.BR);
WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText)));
}
else
{
if (isUseUnsafeModeOnSqlite && !isProc && DataBaseType == DalType.SQLite && !IsOpenTrans)
{
_com.CommandText = "PRAGMA synchronous=Off;" + _com.CommandText;
}
RecordsAffected = _com.ExecuteNonQuery();
}
}
catch (DbException err)
{
string msg = "ExeNonQuery():" + err.Message;
DebugInfo.Append(msg + AppConst.BR);
//recordsAffected = -2;
WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText)));
}
finally
{
if (!IsOpenTrans)
{
CloseCon();
}
}
}
return RecordsAffected;
}
public int ExeNonQuery(string cmdText, bool isProc)
{
SetCommandText(cmdText, isProc);
int rowCount = 0;
//if (_dbOperator.ContainsKey(DataBase))
//{
// if (!CheckIsConcurrent())
// {
// _dbOperator[DataBase] = true;
// rowCount = ExeNonQuerySQL(cmdText, isProc);
// _dbOperator[DataBase] = false;
// }
//}
//else
//{
rowCount = ExeNonQuerySQL(cmdText, isProc);
//}
WriteTime();
return rowCount;
}
private object ExeScalarSQL(string cmdText, bool isProc)
{
object returnValue = null;
ConnBean coSlave = null;
//mssql 有 insert into ...select 操作。
bool isSelectSql = !IsOpenTrans && !cmdText.ToLower().TrimStart().StartsWith("insert ");//&& _IsAllowRecordSql
bool isOpenOK;
if (isSelectSql)
{
coSlave = ConnObj.GetSlave();
isOpenOK = OpenCon(coSlave, AllowConnLevel.MaterBackupSlave);
}
else
{
if (UsingConnBean.IsSlave) // 如果是在从库,切回主库。(insert ...select 操作)
{
ResetConn(ConnObj.Master);
}
isOpenOK = OpenCon();
}
if (isOpenOK)
{
try
{
if (!isSelectSql && UsingConnBean.ConnString != ConnObj.Master.ConnString)
{
RecordsAffected = -2;//从库不允许执行非查询操作。
string msg = "You can't do ExeScalarSQL(with transaction or insert) on Slave DataBase!";
DebugInfo.Append(msg + AppConst.BR);
WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText)));
}
else
{
returnValue = _com.ExecuteScalar();
RecordsAffected = returnValue == null ? 0 : 1;
}
}
catch (DbException err)
{
string msg = "ExeScalar():" + err.Message;
DebugInfo.Append(msg + AppConst.BR);
RecordsAffected = -2;
WriteError(msg + (isProc ? "" : AppConst.BR + GetParaInfo(cmdText)));