Azure Blob Storage下载SQL文件后执行ExecuteNonQuery建表失败
问题原因
- 编码匹配错误:调用
DownloadTextAsync时强制指定了Encoding.UTF8,如果上传到Blob的SQL源文件不是无BOM的UTF-8编码(比如为GBK、UTF-8带BOM、UTF-16等),会触发解码异常,产生不可见字符,甚至将实际换行符转换为字面量\n,最终SQL语法非法无法执行。 - 批处理分隔符不兼容:多数建表SQL脚本会使用
GO作为批处理分隔符,但SqlCommand的ExecuteNonQuery方法原生不识别GO关键字,遇到该关键字会直接抛出语法错误。 - 异步调用方式不规范(非本次报错直接原因):使用
.Result阻塞等待异步方法返回,在部分运行上下文下可能引发线程死锁,也建议同步修复。
修复方案
1. 修正Blob下载解码逻辑
优先下载为字节流再匹配编码处理,避免硬编码编码导致的解码错误,修改后的GetBlob方法参考如下:
public string GetBlob(string fileName) { string connectionString ="constring"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = serviceClient.GetContainerReference("storage"); CloudBlockBlob blob = container.GetBlockBlobReference(fileName); var blobRequestOptions = new BlobRequestOptions { MaximumExecutionTime = TimeSpan.FromMinutes(15), ServerTimeout = TimeSpan.FromHours(1) }; // 先下载为字节数组,避免硬编码编码导致的解码错误 blob.FetchAttributesAsync(null, blobRequestOptions, null).Wait(); byte[] buffer = new byte[blob.Properties.Length]; blob.DownloadToByteArrayAsync(buffer, 0, null, blobRequestOptions, null).Wait(); string contents; // 处理带BOM的UTF-8编码场景 if (buffer.Length >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { contents = Encoding.UTF8.GetString(buffer, 3, buffer.Length - 3); } else { // 可根据SQL源文件实际编码替换,比如Encoding.GetEncoding("GB2312") contents = Encoding.UTF8.GetString(buffer); } // 将异常生成的字面量\n替换为实际换行符 contents = contents.Replace("\\n", "\n").Replace("\\r", "\r").Trim(); return contents; }
2. 兼容SQL批处理分隔符
拆分含GO的脚本分批执行,同时用using语法自动释放数据库连接资源,修改后的执行逻辑参考如下:
try { string scripttocreatetables = blobAccess.GetBlob("test.sql"); // 按GO拆分脚本,不区分大小写,忽略空片段 var sqlSegments = scripttocreatetables.Split(new[] {"GO", "go", "Go"}, StringSplitOptions.RemoveEmptyEntries); // using会自动释放连接,无需手动调用Close using var conn = new SqlConnection(dbstring); conn.Open(); foreach (var segment in sqlSegments) { if (string.IsNullOrWhiteSpace(segment)) continue; using var cmd = new SqlCommand(segment.Trim(), conn); cmd.ExecuteNonQuery(); } } catch (Exception e) { var mh = new MonitorHelper(vcCustomer); var itemid = mh.SetStart("Database"); mh.SetError(itemid, "Database operation failed: " + e.Message); mh.SetEnd(itemid, 0, 0); Console.WriteLine(e.Message); }
3. 可选优化:规范异步调用
将.Wait()/.Result替换为await异步调用,将对应方法改为async标记,可避免线程死锁问题,提升运行性能。
内容的提问来源于stack exchange,提问作者Christian madhan
相关产品推荐
相关产品推荐

