You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

711 lines
27 KiB

3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Text;
  6. using static Apewer.Source.SourceUtility;
  7. #if NETFRAMEWORK
  8. using System.Data.Sql;
  9. #endif
  10. namespace Apewer.Source
  11. {
  12. /// <summary>连接 SQL Server 数据库的客户端。</summary>
  13. [Serializable]
  14. public class SqlClient : DbClient
  15. {
  16. #region connection
  17. private SqlConnection _conn = null;
  18. private string _connstr = "";
  19. /// <summary>使用连接字符串创建数据库连接实例。</summary>
  20. /// <exception cref="ArgumentNullException"></exception>
  21. /// <exception cref="ArgumentException"></exception>
  22. public SqlClient(IDbConnection connection, Timeout timeout = null) : base(timeout)
  23. {
  24. if (connection == null) throw new ArgumentNullException(nameof(connection), "指定的连接无效。");
  25. var conn = connection as SqlConnection;
  26. if (conn == null) throw new ArgumentException(nameof(connection), "指定的连接不是支持的类型。");
  27. _conn = conn;
  28. _connstr = conn.ConnectionString;
  29. }
  30. /// <summary>使用连接字符串创建数据库连接实例。</summary>
  31. public SqlClient(string connectionString, Timeout timeout = null) : base(timeout)
  32. {
  33. _connstr = connectionString ?? "";
  34. }
  35. /// <summary>使用连接凭据创建数据库连接实例。</summary>
  36. /// <exception cref="ArgumentNullException"></exception>
  37. public SqlClient(string address, string store, string user, string pass, Timeout timeout = null) : base(timeout)
  38. {
  39. if (address.IsEmpty()) throw new ArgumentNullException(nameof(address));
  40. if (store.IsEmpty()) store = "master";
  41. var cs = $"data source = {address ?? ""}; initial catalog = {store}; ";
  42. if (string.IsNullOrEmpty(user)) cs += "integrated security = sspi; ";
  43. else
  44. {
  45. cs += $"user id = {user}; ";
  46. if (!string.IsNullOrEmpty(pass)) cs += $"password = {pass}; ";
  47. }
  48. if (timeout != null) cs += $"connection timeout = {timeout.Connect}; ";
  49. _connstr = cs;
  50. }
  51. #endregion
  52. #region override
  53. /// <summary>查询数据库中的所有表名。</summary>
  54. public override string[] TableNames() => QueryStrings("select [name] from [sysobjects] where [type] = 'u' order by [name]");
  55. /// <summary>查询数据库实例中的所有数据库名。</summary>
  56. public override string[] StoreNames() => QueryStrings("select [name] from [master]..[sysdatabases] order by [name]", new string[] { "master", "model", "msdb", "tempdb" });
  57. /// <summary>查询表中的所有列名。</summary>
  58. public override string[] ColumnNames(string tableName) => QueryStrings($"select [name] from [syscolumns] where [id] = object_id('{TextUtility.AntiInject(tableName)}')");
  59. /// <summary>创建表,当表不存在时创建表,当现存表中缺少模型中属性对应的列时增加列。成功时返回空字符串,发生异常时返回异常信息。</summary>
  60. protected override string Initialize(TableStructure structure, string table)
  61. {
  62. var model = structure.Model;
  63. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  64. // 检查现存表。
  65. var exists = false;
  66. var tables = TableNames();
  67. if (tables.Length > 0)
  68. {
  69. var lower = table.ToLower();
  70. foreach (var tn in tables)
  71. {
  72. if (TextUtility.IsEmpty(tn)) continue;
  73. if (tn.ToLower() == lower)
  74. {
  75. exists = true;
  76. break;
  77. }
  78. }
  79. }
  80. if (exists)
  81. {
  82. // 获取已存在的列名。
  83. var columns = ColumnNames(table);
  84. if (columns.Length > 0)
  85. {
  86. var lower = new List<string>();
  87. foreach (var column in columns)
  88. {
  89. if (TextUtility.IsBlank(column)) continue;
  90. lower.Add(column.ToLower());
  91. }
  92. columns = lower.ToArray();
  93. }
  94. // 找出新列。
  95. var newColumns = new List<ColumnAttribute>();
  96. var newPrimaryKey = new List<PrimaryKey>();
  97. foreach (var column in structure.Columns)
  98. {
  99. // 检查 Independent 特性。
  100. if (structure.Independent && column.Independent) continue;
  101. // 去重。
  102. var lower = column.Field.ToLower();
  103. if (columns.Contains(lower)) continue;
  104. var type = Declaration(column);
  105. if (string.IsNullOrEmpty(type)) return $"类型 {column.Type} 不受支持。";
  106. newColumns.Add(column);
  107. }
  108. // 执行:添加列。
  109. if (newColumns.IsEmpty()) return TextUtility.Empty;
  110. foreach (var column in newColumns)
  111. {
  112. var type = Declaration(column);
  113. var sql = $"alter table [{table}] add {type}; ";
  114. var execute = Execute(sql, null, false);
  115. if (!execute.Success) return execute.Message;
  116. }
  117. return TextUtility.Empty;
  118. }
  119. else
  120. {
  121. var sqlcolumns = new List<string>();
  122. foreach (var column in structure.Columns)
  123. {
  124. // 检查 Independent 特性。
  125. if (structure.Independent && column.Independent) continue;
  126. var type = Declaration(column);
  127. if (!column.Independent)
  128. {
  129. if (column.PrimaryKey) type = type + " primary key";
  130. if (column.Incremental) type += " identity";
  131. }
  132. if (string.IsNullOrEmpty(type)) return TextUtility.Merge("类型 ", column.Type.ToString(), " 不受支持。");
  133. sqlcolumns.Add(type);
  134. }
  135. if (sqlcolumns.Count < 1) return $"无法对类型 {model.FullName} 创建表:没有定义任何字段。";
  136. var sql = TextUtility.Merge("create table [", table, "](", string.Join(", ", sqlcolumns.ToArray()), "); ");
  137. var execute = Execute(sql, null, false);
  138. if (execute.Success) return TextUtility.Empty;
  139. return execute.Message;
  140. }
  141. }
  142. /// <summary>插入记录。返回错误信息。</summary>
  143. public override string Insert(object record, string table = null, bool adjust = true)
  144. {
  145. if (record == null) return "参数无效。";
  146. if (adjust) FixProperties(record);
  147. var structure = TableStructure.Parse(record.GetType());
  148. if (structure == null) return "无法解析记录模型。";
  149. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  150. if (string.IsNullOrEmpty(table)) return "表名称无效。";
  151. // 排除字段。
  152. var excluded = new List<string>();
  153. foreach (var ca in structure.Columns)
  154. {
  155. // 排除不使用 ORM 的属性。
  156. if (ca.Independent || ca.Incremental) excluded.Add(ca.Field);
  157. }
  158. var ps = structure.CreateParameters(record, Parameter, excluded);
  159. var psc = ps.Length;
  160. if (psc < 1) return "数据模型不包含字段。";
  161. var names = new List<string>(psc);
  162. var values = new List<string>(psc);
  163. foreach (var column in ps)
  164. {
  165. names.Add($"[{column.ParameterName}]");
  166. values.Add("@" + column.ParameterName);
  167. }
  168. var sb = new StringBuilder();
  169. sb.Append("insert into ", table, "(", string.Join(", ", names.ToArray()), ") ");
  170. sb.Append("values(", string.Join(", ", values.ToArray()), "); ");
  171. var sql = sb.ToString();
  172. var execute = Execute(sql, ps, false);
  173. if (execute.Success) return TextUtility.Empty;
  174. return execute.Message;
  175. }
  176. /// <summary>更新记录,实体中的 Key 属性不被更新。返回错误信息。</summary>
  177. /// <remarks>不更新带有 Independent 特性的模型(缺少 Key 属性)。</remarks>
  178. public override string Update(IRecord record, string table = null, bool adjust = true)
  179. {
  180. if (record == null) return "参数无效。";
  181. if (adjust)
  182. {
  183. FixProperties(record);
  184. SetUpdated(record);
  185. }
  186. var structure = TableStructure.Parse(record.GetType());
  187. if (structure == null) return "无法解析记录模型。";
  188. if (structure.Independent) return "无法更新带有 Independent 特性的模型。";
  189. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  190. if (string.IsNullOrEmpty(table)) return "表名称无效。";
  191. // 排除字段。
  192. var excluded = new List<string>();
  193. if (structure.Key != null) excluded.Add(structure.Key.Field);
  194. foreach (var ca in structure.Columns)
  195. {
  196. // 排除不使用 ORM 的属性、自增属性和主键属性。
  197. if (ca.Independent || ca.Incremental || ca.PrimaryKey || ca.NoUpdate) excluded.Add(ca.Field);
  198. }
  199. var ps = structure.CreateParameters(record, Parameter, excluded);
  200. var psc = ps.Length;
  201. if (psc < 1) return "数据模型不包含字段。";
  202. var items = new List<string>();
  203. foreach (var p in ps)
  204. {
  205. var pn = p.ParameterName;
  206. items.Add($"[{pn}] = @{pn}");
  207. }
  208. var key = record.Key.SafeKey();
  209. var sql = $"update {table} set {string.Join(", ", items.ToArray())} where [{structure.Key.Field}]='{key}'";
  210. var execute = Execute(sql, ps, false);
  211. if (execute.Success) return TextUtility.Empty;
  212. return execute.Message;
  213. }
  214. /// <summary></summary>
  215. public override string ConnectionString => _connstr;
  216. /// <summary></summary>
  217. protected override IDataAdapter CreateDataAdapter(IDbCommand command) => new SqlDataAdapter((SqlCommand)command);
  218. /// <summary></summary>
  219. protected override IDbConnection GetConnection()
  220. {
  221. if (_conn == null) _conn = new SqlConnection(_connstr);
  222. return _conn;
  223. }
  224. /// <summary></summary>
  225. protected override IDataParameter CreateParameter() => new SqlParameter();
  226. /// <summary></summary>
  227. protected override string Keys(string tableName, string keyField, string flagField, long flagValue)
  228. {
  229. if (flagValue == 0) return $"select [{keyField}] from [{tableName}]";
  230. else return $"select [{keyField}] from [{tableName}] where [{flagField}] = {flagValue}";
  231. }
  232. /// <summary></summary>
  233. protected override string Get(string tableName, string keyField, string keyValue, string flagField, long flagValue)
  234. {
  235. if (flagValue == 0) return $"select top 1 * from [{tableName}] where [{keyField}] = '{keyValue}'";
  236. else return $"select top 1 * from [{tableName}] where [{keyField}] = '{keyValue}' and [{flagField}] = {flagValue}";
  237. }
  238. /// <summary></summary>
  239. protected override string List(string tableName, string flagField, long flagValue)
  240. {
  241. if (flagValue == 0) return $"select * from [{tableName}]";
  242. else return $"select * from [{tableName}] where [{flagField}] = {flagValue}";
  243. }
  244. #endregion
  245. #region special
  246. /// <summary>清空与指定连接关联的连接池。</summary>
  247. public static void ClearPool(IDbConnection connection)
  248. {
  249. var special = connection as SqlConnection;
  250. if (special != null)
  251. {
  252. try
  253. {
  254. SqlConnection.ClearPool(special);
  255. }
  256. catch { }
  257. }
  258. }
  259. /// <summary>清空与指定连接关联的连接池。</summary>
  260. public static void ClearPool(IDbAdo instance)
  261. {
  262. var connection = instance?.Connection;
  263. if (connection != null) ClearPool(connection);
  264. }
  265. /// <summary>清空连接池。</summary>
  266. public static void ClearAllPools()
  267. {
  268. try
  269. {
  270. SqlConnection.ClearAllPools();
  271. }
  272. catch { }
  273. }
  274. /// <summary>获取列信息。</summary>
  275. public ColumnInfo[] ColumnsInfo(string tableName)
  276. {
  277. if (tableName.IsEmpty()) throw new ArgumentNullException(nameof(tableName));
  278. var sql = $"select name, xtype, length from syscolumns where id = object_id('{tableName}') ";
  279. using (var query = Query(sql))
  280. {
  281. var ab = new ArrayBuilder<ColumnInfo>();
  282. for (var i = 0; i < query.Rows; i++)
  283. {
  284. var info = new ColumnInfo();
  285. info.Name = query.Text(i, "name");
  286. info.Type = XType(query.Int32(i, "xtype"));
  287. info.Length = query.Int32(i, "length");
  288. ab.Add(info);
  289. }
  290. return ab.Export();
  291. }
  292. }
  293. /// <summary>批量插入,必须在 DataTable 中指定表名,或指定 tableName 参数。</summary>
  294. /// <exception cref="ArgumentNullException"></exception>
  295. /// <exception cref="ArgumentException"></exception>
  296. /// <exception cref="Exception"></exception>
  297. public void BulkCopy(DataTable table, string tableName = null)
  298. {
  299. // 检查 table 参数。
  300. if (table == null) throw new ArgumentNullException(nameof(table));
  301. if (table.Rows.Count < 1) return;
  302. // 检查 tableName 参数。
  303. if (tableName.IsEmpty()) tableName = table.TableName;
  304. if (tableName.IsEmpty()) throw new ArgumentException("未指定表名。");
  305. // 连接数据库。
  306. var connect = Connect();
  307. if (connect.NotEmpty()) throw new Exception(connect);
  308. // 准备参数。
  309. var options = SqlBulkCopyOptions.Default;
  310. var trans = Transaction as SqlTransaction;
  311. if (trans == null) options |= SqlBulkCopyOptions.UseInternalTransaction;
  312. // 批量插入。
  313. var bc = null as SqlBulkCopy;
  314. try
  315. {
  316. bc = new SqlBulkCopy((SqlConnection)Connection, options, trans);
  317. bc.DestinationTableName = tableName;
  318. bc.BatchSize = table.Rows.Count;
  319. bc.WriteToServer(table);
  320. try { bc.Close(); } catch { }
  321. }
  322. catch (Exception ex)
  323. {
  324. try { bc.Close(); } catch { }
  325. throw ex;
  326. }
  327. }
  328. /// <summary>创建数据库,返回错误信息。</summary>
  329. /// <param name="name">数据库名称。</param>
  330. /// <param name="logMaxSizeMB">日志文件的最大 MB 数,指定非正数将不限制增长。</param>
  331. /// <returns>成功时候返回 NULL 值,失败时返回错误信息。</returns>
  332. public string CreateStore(string name, int logMaxSizeMB = 1024)
  333. {
  334. var store = name.Escape().ToTrim();
  335. if (store.IsEmpty()) return "创建失败:未指定数据库名称。";
  336. if (ConnectionString.IsEmpty()) return "创建失败:未指定数据库连接方式。";
  337. using (var source = new SqlClient(ConnectionString))
  338. {
  339. var connect = source.Connect();
  340. if (connect.NotEmpty()) return "创建失败:" + connect;
  341. var schema = source.Cell("select default_schema_name from sys.database_principals where type = 'S' and name=user_name()");
  342. if (schema.IsEmpty()) return "创建失败:无法获取默认模式名称。";
  343. var refPath = source.Cell(@"select f.physical_name path from sys.filegroups g left join sys.database_files f on f.data_space_id = g.data_space_id where g.name = 'PRIMARY' and g.type = 'FG' and g.is_default = 1 and g.filegroup_guid is null");
  344. if (refPath.IsEmpty()) return "创建失败:无法获取文件路径。";
  345. var win = refPath.Substring(1, 2) == ":\\";
  346. var nix = refPath.StartsWith("/");
  347. if (!win && !nix) return "创建失败:暂不支持该服务器。";
  348. var mdfPath = store + ".mdf";
  349. var ldfPath = store + ".ldf";
  350. if (win)
  351. {
  352. var refSplit = refPath.Split('\\');
  353. var dir = string.Join("\\", refSplit, 0, refSplit.Length - 1);
  354. mdfPath = dir + "\\" + mdfPath;
  355. ldfPath = dir + "\\" + ldfPath;
  356. }
  357. if (nix)
  358. {
  359. var refSplit = refPath.Split('/');
  360. var dir = string.Join("/", refSplit, 0, refSplit.Length - 1);
  361. mdfPath = dir + "/" + mdfPath;
  362. ldfPath = dir + "/" + ldfPath;
  363. }
  364. // 创建库。
  365. var maxLog = logMaxSizeMB > 0 ? $"{logMaxSizeMB}MB" : "UNLIMITED";
  366. var sql1 = $@"
  367. CREATE DATABASE [{store}]
  368. ON PRIMARY
  369. (
  370. NAME = N'{store}',
  371. FILENAME = N'{mdfPath}',
  372. SIZE = 4MB,
  373. MAXSIZE = UNLIMITED,
  374. FILEGROWTH = 4MB
  375. )
  376. LOG ON
  377. (
  378. NAME = N'{store}_log',
  379. FILENAME = N'{ldfPath}',
  380. SIZE = 1MB,
  381. MAXSIZE = {maxLog},
  382. FILEGROWTH = 1MB
  383. )
  384. COLLATE Chinese_PRC_CI_AS
  385. ";
  386. var create = source.Execute(sql1, null, false);
  387. if (!create.Success) return TextUtility.Merge("创建失败:", create.Message);
  388. // 设置兼容性级别。
  389. var sql2 = $"alter database [{store}] set compatibility_level = 100";
  390. source.Execute(sql2, null, false);
  391. // 设置恢复默认为“简单”
  392. var sql3 = $"alter database [{store}] set recovery simple";
  393. source.Execute(sql3, null, false);
  394. return null;
  395. }
  396. }
  397. static string XType(int xtype)
  398. {
  399. switch (xtype)
  400. {
  401. case 34: return "image";
  402. case 35: return "text";
  403. case 36: return "uniqueidentifier";
  404. case 48: return "tinyint";
  405. case 52: return "smallint";
  406. case 56: return "int";
  407. case 58: return "smalldatetime";
  408. case 59: return "real";
  409. case 60: return "money";
  410. case 61: return "datetime";
  411. case 62: return "float";
  412. case 98: return "sql_variant";
  413. case 99: return "ntext";
  414. case 104: return "bit";
  415. case 106: return "decimal";
  416. case 108: return "numeric";
  417. case 122: return "smallmoney";
  418. case 127: return "bigint";
  419. case 165: return "varbinary";
  420. case 167: return "varchar";
  421. case 173: return "binary";
  422. case 175: return "char";
  423. case 189: return "timestamp";
  424. case 231: return "nvarchar";
  425. case 239: return "nchar";
  426. case 241: return "xml";
  427. }
  428. return null;
  429. }
  430. #if NET20 || NET40
  431. /// <summary>枚举本地网络中的 SQL Server 实例的信息。</summary>
  432. public static Source[] EnumerateSources()
  433. {
  434. var list = new List<Source>();
  435. // 表中列名:ServerName、InstanceName、IsClustered、Version。
  436. using (var table = SqlDataSourceEnumerator.Instance.GetDataSources())
  437. {
  438. var query = new Query(table);
  439. var rows = query.Rows;
  440. list.Capacity = rows;
  441. for (int i = 0; i < rows; i++)
  442. {
  443. var item = new Source();
  444. item.ServerName = query.Text(i, "ServerName");
  445. list.Add(item);
  446. }
  447. }
  448. return list.ToArray();
  449. }
  450. /// <summary>SQL Server 实例的信息。</summary>
  451. public sealed class Source
  452. {
  453. /// <summary></summary>
  454. public string ServerName { get; set; }
  455. /// <summary></summary>
  456. public string InstanceName { get; set; }
  457. /// <summary></summary>
  458. public string IsClustered { get; set; }
  459. /// <summary></summary>
  460. public string Version { get; set; }
  461. }
  462. #endif
  463. /// <summary>创建参数。</summary>
  464. /// <exception cref="ArgumentNullException"></exception>
  465. /// <exception cref="InvalidOperationException"></exception>
  466. static SqlParameter Parameter(Parameter parameter)
  467. {
  468. if (parameter == null) throw new InvalidOperationException("参数无效。");
  469. return Parameter(parameter.Name, parameter.Type, parameter.Size, parameter.Value);
  470. }
  471. /// <summary>创建参数。</summary>
  472. public static SqlParameter Parameter(string name, ColumnType type, int size, object value)
  473. {
  474. var vname = TextUtility.Trim(name);
  475. if (TextUtility.IsBlank(vname)) return null;
  476. var vtype = SqlDbType.BigInt;
  477. switch (type)
  478. {
  479. case ColumnType.Boolean:
  480. vtype = SqlDbType.Bit;
  481. break;
  482. case ColumnType.Bytes:
  483. vtype = SqlDbType.Image;
  484. break;
  485. case ColumnType.Integer:
  486. vtype = SqlDbType.BigInt;
  487. break;
  488. case ColumnType.Float:
  489. vtype = SqlDbType.Float;
  490. break;
  491. case ColumnType.DateTime:
  492. vtype = SqlDbType.DateTime;
  493. break;
  494. case ColumnType.VarChar:
  495. case ColumnType.VarChar191:
  496. case ColumnType.VarCharMax:
  497. vtype = SqlDbType.VarChar;
  498. break;
  499. case ColumnType.NVarChar:
  500. case ColumnType.NVarChar191:
  501. case ColumnType.NVarCharMax:
  502. vtype = SqlDbType.NVarChar;
  503. break;
  504. case ColumnType.Text:
  505. vtype = SqlDbType.Text;
  506. break;
  507. case ColumnType.NText:
  508. vtype = SqlDbType.NText;
  509. break;
  510. default:
  511. throw new InvalidOperationException(TextUtility.Merge("类型 ", type.ToString(), " 不受支持。"));
  512. }
  513. var vsize = size;
  514. switch (type)
  515. {
  516. case ColumnType.VarChar:
  517. vsize = NumberUtility.Restrict(vsize, 0, 8000);
  518. break;
  519. case ColumnType.NVarChar:
  520. vsize = NumberUtility.Restrict(vsize, 0, 4000);
  521. break;
  522. case ColumnType.VarChar191:
  523. case ColumnType.NVarChar191:
  524. vsize = NumberUtility.Restrict(vsize, 0, 191);
  525. break;
  526. default:
  527. vsize = 0;
  528. break;
  529. }
  530. var vvalue = value ?? DBNull.Value;
  531. if (vvalue is string && vvalue != null && vsize > 0)
  532. {
  533. vvalue = TextUtility.Left((string)vvalue, vsize);
  534. }
  535. var parameter = new SqlParameter();
  536. parameter.ParameterName = vname;
  537. parameter.SqlDbType = vtype;
  538. parameter.Value = vvalue;
  539. if (vsize > 0) parameter.Size = vsize;
  540. return parameter;
  541. }
  542. /// <summary>创建参数。</summary>
  543. public static SqlParameter Parameter(string name, SqlDbType type, int size, object value)
  544. {
  545. if (value is string && value != null && size > 0)
  546. {
  547. value = TextUtility.Left((string)value, (int)size);
  548. }
  549. var p = new SqlParameter();
  550. p.ParameterName = name ?? "";
  551. p.SqlDbType = type;
  552. p.Size = size;
  553. p.Value = value ?? DBNull.Value;
  554. return p;
  555. }
  556. /// <summary>创建参数。</summary>
  557. public static SqlParameter Parameter(string name, SqlDbType type, object value)
  558. {
  559. var p = new SqlParameter();
  560. p.ParameterName = name ?? "";
  561. p.SqlDbType = type;
  562. p.Value = value ?? DBNull.Value;
  563. return p;
  564. }
  565. static string Declaration(ColumnAttribute column)
  566. {
  567. var type = TextUtility.Empty;
  568. var vcolumn = column;
  569. var length = Math.Max(0, vcolumn.Length);
  570. switch (vcolumn.Type)
  571. {
  572. case ColumnType.Boolean:
  573. type = "bit";
  574. break;
  575. case ColumnType.Integer:
  576. type = "bigint";
  577. break;
  578. case ColumnType.Float:
  579. type = "float";
  580. break;
  581. case ColumnType.Bytes:
  582. type = "image";
  583. break;
  584. case ColumnType.DateTime:
  585. type = "datetime";
  586. break;
  587. case ColumnType.VarChar:
  588. type = $"varchar({Math.Min(8000, length)})";
  589. break;
  590. case ColumnType.VarChar191:
  591. type = "varchar(191)";
  592. break;
  593. case ColumnType.VarCharMax:
  594. type = "varchar(max)";
  595. break;
  596. case ColumnType.Text:
  597. type = "text";
  598. break;
  599. case ColumnType.NVarChar:
  600. type = $"nvarchar({Math.Min(4000, length)})";
  601. break;
  602. case ColumnType.NVarChar191:
  603. type = "nvarchar(191)";
  604. break;
  605. case ColumnType.NVarCharMax:
  606. type = "nvarchar(max)";
  607. break;
  608. case ColumnType.NText:
  609. type = "ntext";
  610. break;
  611. default:
  612. return TextUtility.Empty;
  613. }
  614. return $"[{vcolumn.Field}] {type}";
  615. }
  616. #endregion
  617. }
  618. }