下面是自己凑的代码,需要建立数据源,可以执行,有没有不需要设置数据源的方法?
因为我这里需要在客户机上执行.sql文件,所以需要一个可以直接执行.SQL的小工具。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
namespace DoSQL
{
public partial class FrmSQL : Form
{
public FrmSQL()
{
InitializeComponent();
}
string file=string.Empty;
private void btnQuery_Click(object sender, EventArgs e)
{
SelectSQLFile();
}
private void SelectSQLFile()
{
string fileName = string.Empty;
string exName = string.Empty;
this.openFileDialog1.Filter = "SQL 脚本|*.sql";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = this.openFileDialog1.FileName;
exName = Path.GetExtension(fileName);
if (exName.ToLower() == ".sql")
{
this.txtSQL.Text = fileName;
file = fileName;
}
else
{
MessageBox.Show("必须选择.sql格式文件!");
}
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string SerName = string.Empty;
string DatName = string.Empty;
string Sid = string.Empty;
string Psw = string.Empty;
if (this.txtServerName.Text == "" && this.txtDataBaseName.Text == "")
{
MessageBox.Show("请输入服务器名和数据源名!");
return;
}
if (file == "")
{
MessageBox.Show("请先选择.sql文件!");
return;
}
try
{
SerName = this.txtServerName.Text.ToString().Trim();
DatName = this.txtDataBaseName.Text.ToString().Trim();
Sid = this.txtName.Text.ToString().Trim();
Psw = this.txtPassW.Text.ToString().Trim();
string sqlQuery = "osql -U " + Sid + " -P " + Psw + " -S " + SerName + " -D " + DatName + " -i " + file + "";
//osql方式必须与ODBC数据源合用,所以使用的机器上必须添加ODBC数据源,而且要注意选择默认数据库
string strRst = ExeCommand(sqlQuery);
Console.WriteLine(strRst);
Console.ReadLine();
}
catch (Exception err)
{
MessageBox.Show(err.ToString ());
}
}
public static string ExeCommand(string commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
strOutput = e.Message;
}
return strOutput;
}
}
}