执行sql文件中内容

using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebApplication2
{
public class Class : IHostedService
{
public Class()
{

}

public string ProceedSqlScripts()
{
try
{
List<string> statements = new List<string>();
string genlujing = Directory.GetCurrentDirectory();
string rootPath = Path.Combine(genlujing, "SqlFile");
string path = Path.Combine(rootPath, "wenjian");
using (Stream stream = File.OpenRead(path))
using (StreamReader reader = new StreamReader(stream))
{
string statement = string.Empty;
while ((statement = ReadNextStatementFromStream(reader))!= null)
{
statements.Add(statement);
}
}
string str = string.Empty;
foreach (var item in statements)
{
str += item;
}


//执行str 的sql语句,用ADO EFCore 什么的

 

return str;
}
catch (Exception)
{

throw;
}
}
public string ReadNextStatementFromStream(StreamReader reader)
{
StringBuilder sb = new StringBuilder();
string lineOfText;
while (true)
{
lineOfText = reader.ReadLine();
if (lineOfText == null)
{
if (sb.Length > 0)
return sb.ToString();
else
return null;
}
if (string.IsNullOrEmpty(lineOfText))
{
continue;
}
sb.Append(lineOfText + Environment.NewLine);
}
return sb.ToString();
}

public async Task StartAsync(CancellationToken cancellationToken)
{
ProceedSqlScripts();
await Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
}

posted @ 2022-07-14 16:20  Best丶zhaotf  阅读(33)  评论(0编辑  收藏  举报