ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C# 调用*.sql第一种

C# 调用*.sql第一种

原创 Linux操作系统 作者:iDotNetSpace 时间:2009-01-04 15:52:48 0 删除 编辑
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/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5322972