DBAccess.cs
using System;
using System.Xml;
using System.Data;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ExecuteSqlFile
{
public class DBAccess
{
public DBAccess()
{
}
#region 屬性
private static string ConStr = "";
public static string ConString
{
get
{
return ConStr;
}
set
{
ConStr = value;
}
}
private static SqlConnection Con;
public static SqlConnection MyConnection
{
get
{
if (Con == null)
{
Con = new SqlConnection(ConString);
}
return Con;
}
}
#endregion
public static bool ExecuteSqlFile(string varFileName)
{
if (!File.Exists(varFileName))
{
return false;
}
StreamReader sr = File.OpenText(varFileName);
ArrayList alSql = new ArrayList();
string commandText = "";
string varLine = "";
while (sr.Peek() > -1)
{
varLine = sr.ReadLine();
if (varLine == "")
{
continue;
}
if (varLine != "GO")
{
commandText += varLine;
commandText += " ";
}
else
{
alSql.Add(commandText);
commandText = "";
}
}
sr.Close();
try
{
ExecuteCommand(alSql);
}
catch(Exception ex)
{
throw ex;
}
return true;
}
private static void ExecuteCommand(ArrayList varSqlList)
{
MyConnection.Open();
SqlTransaction varTrans = MyConnection.BeginTransaction();
SqlCommand command = new SqlCommand();
command.Connection = MyConnection;
command.Transaction = varTrans;
try
{
foreach (string varcommandText in varSqlList)
{
command.CommandText = varcommandText;
command.ExecuteNonQuery();
}
varTrans.Commit();
}
catch (Exception ex)
{
varTrans.Rollback();
throw ex;
}
finally
{
MyConnection.Close();
}
}
public static bool ExecOSQL(string sServer,string sUser,string sPwd,string sSqlFile)
{
try
{
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 Parameter = "osql.exe -U " + sUser + " -P "+ sPwd + " -S " + sServer + " -i " + sSqlFile;
p.Start();
p.StandardInput.WriteLine(Parameter);
p.StandardInput.WriteLine( "exit ");
p.StandardInput.WriteLine( "exit ");
p.WaitForExit();
p.Close();
}
catch(Exception ex)
{
throw ex;
}
return true;
}
}
}
Call it
- protected void btnExecSQL_Click(object sender, EventArgs e)
- {
- try
- {
- ExecuteSqlFile.DBAccess.ConString = "server=TEST;uid=sa;pwd=1234567890;database=master";
- if(ExecuteSqlFile.DBAccess.ExecOSQL("TEST","sa","1234567890",Server.MapPath("CreaDB.sql")))
- {
- lbInfo.Text += "Create DB OK!";
-
- if (ExecuteSqlFile.DBAccess.ExecuteSqlFile(Server.MapPath("iTest.sql")))
- {
- lbInfo.Text += "Create Table OK!";
- }
- else
- {
- lbInfo.Text += "Create Table Err!";
- }
- }
- else
- {
- lbInfo.Text += "Create DB Err!";
- }
- }
- catch(Exception ex)
- {
- lbInfo.Text += ex.Message;
- }
- }