IDbConnection_MsSqlExtensions.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System.Data;
  2. using Dapper;
  3. using System;
  4. using System.Data.SqlClient;
  5. using Vit.Extensions;
  6. using Vit.Core.Module.Log;
  7. using Vit.Orm.Dapper;
  8. namespace Vit.Db.DbMng.Extendsions
  9. {
  10. public static partial class IDbConnection_MsSqlExtensions
  11. {
  12. /*
  13. --------------------------------------------------------------------------------------
  14. 先读后写
  15. declare @fileContent varbinary(MAX);
  16. select @fileContent=BulkColumn from OPENROWSET(BULK 'T:\机电合并.zip', SINGLE_BLOB) as content;
  17. if Exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'sqler_temp_filebuffer') and xtype='U')
  18. drop table sqler_temp_filebuffer;
  19. select @fileContent as fileContent into sqler_temp_filebuffer;
  20. exec master..xp_cmdshell 'bcp "select null union all select ''0'' union all select ''0'' union all select null union all select ''n'' union all select null " queryout "T:\file.fmt" /T /c'
  21. exec master..xp_cmdshell 'BCP "SELECT fileContent FROM sqler_temp_filebuffer" queryout "T:\file.zip" -T -i "T:\file.fmt"'
  22. if Exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'sqler_temp_filebuffer') and xtype='U')
  23. drop table sqler_temp_filebuffer;
  24. */
  25. #region MsSql_ReadFileFromDisk
  26. /// <summary>
  27. /// 从磁盘读取文件内容
  28. /// </summary>
  29. /// <param name="conn"></param>
  30. /// <param name="filePath"></param>
  31. /// <returns></returns>
  32. public static byte[] MsSql_ReadFileFromDisk(this IDbConnection conn, string filePath)
  33. {
  34. /* select BulkColumn from OPENROWSET(BULK N'T:\机电合并.zip', SINGLE_BLOB) as content;
  35. */
  36. return conn.MsSql_RunUseMaster((c) =>
  37. {
  38. return conn.ExecuteScalar<byte[]>(
  39. " select BulkColumn from OPENROWSET(BULK N'"+ filePath + "', SINGLE_BLOB) as content"
  40. ,commandTimeout: DapperConfig.CommandTimeout);
  41. });
  42. }
  43. #endregion
  44. #region MsSql_DeleteFileFromDisk
  45. /// <summary>
  46. /// 从磁盘删除文件
  47. /// </summary>
  48. /// <param name="conn"></param>
  49. /// <param name="filePath"></param>
  50. /// <returns></returns>
  51. public static void MsSql_DeleteFileFromDisk(this IDbConnection conn, string filePath)
  52. {
  53. conn.MsSql_Cmdshell("del \""+ filePath + "\"");
  54. }
  55. #endregion
  56. #region MsSql_WriteFileToDisk
  57. /// <summary>
  58. /// 写入文件到磁盘
  59. /// </summary>
  60. /// <param name="conn"></param>
  61. /// <param name="filePath"></param>
  62. /// <param name="fileContent"></param>
  63. public static void MsSql_WriteFileToDisk(this IDbConnection conn, string filePath,byte[]fileContent)
  64. {
  65. string fmtFilePath = filePath + ".sqler.temp.fmt";
  66. conn.MsSql_Cmdshell(runCmd => {
  67. #region (x.1)把文件内容写入到临时表
  68. conn.Execute(@"
  69. if Exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'sqler_temp_filebuffer') and xtype='U')
  70. drop table sqler_temp_filebuffer;
  71. select @fileContent as fileContent into sqler_temp_filebuffer;
  72. ",new { fileContent }, commandTimeout: DapperConfig.CommandTimeout);
  73. #endregion
  74. try
  75. {
  76. #region (x.2)写入二进制文件到磁盘
  77. var log1 = runCmd("bcp \"select null union all select '0' union all select '0' union all select null union all select 'n' union all select null \" queryout \""+ fmtFilePath + "\" /T /c");
  78. Logger.Info("[sqler]-MsSqlMng 写入文件到磁盘. 创建fmt文件,outlog: " + log1.Serialize());
  79. var log2 = runCmd("BCP \"SELECT fileContent FROM sqler_temp_filebuffer\" queryout \"" + filePath + "\" -T -i \"" + fmtFilePath + "\"");
  80. Logger.Info("[sqler]-MsSqlMng 写入文件到磁盘.创建文件,outlog: " + log2.Serialize());
  81. #endregion
  82. }
  83. finally
  84. {
  85. //(x.1)删除fmt文件
  86. try
  87. {
  88. runCmd("del \"" + fmtFilePath + "\"");
  89. }
  90. catch (Exception ex)
  91. {
  92. Logger.Error(ex);
  93. }
  94. //(x.2)删除临时表
  95. conn.Execute(@"
  96. if Exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'sqler_temp_filebuffer') and xtype='U')
  97. drop table sqler_temp_filebuffer;
  98. ", commandTimeout: DapperConfig.CommandTimeout);
  99. }
  100. });
  101. }
  102. #endregion
  103. #region MsSql_RunUseMaster
  104. public static T MsSql_RunUseMaster<T>(this IDbConnection conn, Func<IDbConnection, T> run)
  105. {
  106. string oriConnectionString = conn.ConnectionString;
  107. try
  108. {
  109. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(oriConnectionString);
  110. builder.InitialCatalog = "";
  111. conn.ConnectionString = builder.ToString();
  112. return run(conn);
  113. }
  114. finally
  115. {
  116. conn.ConnectionString = oriConnectionString;
  117. }
  118. }
  119. #endregion
  120. #region MsSql_Cmdshell
  121. public static DataTable MsSql_Cmdshell(this IDbConnection conn, string cmd)
  122. {
  123. DataTable dt = null;
  124. conn.MsSql_Cmdshell( runCmd=> dt = runCmd(cmd) );
  125. return dt;
  126. }
  127. public static void MsSql_Cmdshell(this IDbConnection conn, Action<Func<string,DataTable>> handleToRun)
  128. {
  129. conn.MsSql_RunUseMaster((c)=> {
  130. bool advancedOptionsIsOpened = false;
  131. try
  132. {
  133. advancedOptionsIsOpened = c.ExecuteDataTable("EXEC SP_CONFIGURE 'show advanced options'").Rows[0]["config_value"]?.Convert<string>() != "0";
  134. }
  135. catch (Exception)
  136. {
  137. }
  138. bool cmdshellIsOpened = false;
  139. try
  140. {
  141. cmdshellIsOpened = c.ExecuteDataTable("EXEC SP_CONFIGURE 'xp_cmdshell'").Rows[0]["config_value"]?.Convert<string>() != "0";
  142. }
  143. catch (Exception)
  144. {
  145. }
  146. try
  147. {
  148. if (!advancedOptionsIsOpened)
  149. c.Execute(@"
  150. --打开高级选项
  151. EXEC SP_CONFIGURE 'show advanced options', 1;
  152. RECONFIGURE;
  153. ", commandTimeout: Orm.Dapper.DapperConfig.CommandTimeout);
  154. if (!cmdshellIsOpened)
  155. c.Execute(@"
  156. --启用执行CMD命令
  157. EXEC SP_CONFIGURE 'xp_cmdshell', 1;
  158. RECONFIGURE;
  159. ", commandTimeout: Orm.Dapper.DapperConfig.CommandTimeout);
  160. Func<string, DataTable> runCmd = (cmd) => c.ExecuteDataTable("exec master..xp_cmdshell @cmd ", new { cmd });
  161. handleToRun(runCmd);
  162. return true;
  163. }
  164. finally
  165. {
  166. if(!cmdshellIsOpened)
  167. c.Execute(@"
  168. --关闭执行CMD命令
  169. EXEC SP_CONFIGURE 'xp_cmdshell', 0;
  170. RECONFIGURE;
  171. ", commandTimeout: Orm.Dapper.DapperConfig.CommandTimeout);
  172. if (!advancedOptionsIsOpened)
  173. c.Execute(@"
  174. --关闭高级选项
  175. EXEC SP_CONFIGURE 'show advanced options', 0;
  176. RECONFIGURE;
  177. ", commandTimeout: Orm.Dapper.DapperConfig.CommandTimeout);
  178. }
  179. });
  180. }
  181. #endregion
  182. }
  183. }