C# 呼叫*.sql第一種

iDotNetSpace發表於2009-01-04
using System;
using System.Xml;
using System.Data;
using System.IO;
using System.Collections;
using System.Data.SqlClient;

namespace ExecuteSqlFile
{
///
/// DBAccess 的摘要說明。
///

public class DBAccess
{
public DBAccess()
{
}

#region 屬性

private static string ConStr = "";

private static string ConString
{
get
{
if(ConStr == "")
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("ServerConfig.xml");

string userid = doc.SelectSingleNode("ServerConfig/UserId").InnerText;
string password = doc.SelectSingleNode("ServerConfig/PassWord").InnerText;
string servername = doc.SelectSingleNode("ServerConfig/ServerName").InnerText;
string database = doc.SelectSingleNode("ServerConfig/DataBase").InnerText;
ConStr = "server = " + servername + ";uid = "
+ userid + ";pwd = " + password + ";database = " + database;
}
catch(Exception ex)
{
throw ex;
}
}

return ConStr;
}
}

private static SqlConnection Con;


public static SqlConnection MyConnection
{
get
{
if(Con == null)
{
Con = new SqlConnection(ConString);
}
return Con;
}
}

#endregion


///
/// 執行Sql檔案
///

/// 檔案的名稱
///
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 += "\r\n";
}
else
{
alSql.Add(commandText);
commandText = "";
}
}

sr.Close();

try
{
ExecuteCommand(alSql);
}
catch
{
return false;
}

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();
}
}
}
}



配置檔案如下:


localhost
tttttt
sa
sa

儲存為ServerConfig.xml
放到Bin/Debug/裡面

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-526510/,如需轉載,請註明出處,否則將追究法律責任。

相關文章