C#中如何执行sql脚本?

来源:互联网 发布:衣柜造型设计软件 编辑:程序博客网 时间:2024/06/08 07:07

在C#中执行SQL脚本,可以考虑使用osql工具。
Example :
#region 调用Osql.exe执行建库脚本
/// <summary>
/// 调用Osql.exe执行建库脚本
/// </summary>
/// <param name="UserName">数据库访问用户名</param>
/// <param name="Pwd">数据库访问密码</param>

private void CreateDataBase ()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string Path = Application.StartupPath.ToString();
string Parameter = "osql.exe -U " + uid + " -P " + pwd + " -S  "+ ServerName +" -i " + Path + @"/IPMS.sql";
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
p.Start();
p.StandardInput.WriteLine(Parameter);
p.StandardInput.WriteLine("exit");
p.StandardInput.WriteLine("exit");
p.WaitForExit();
p.Close();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
this.Close();
}
}