C#执⾏sql⽂件运⾏sql⽂件
private void metroButton2_Click(object sender, EventArgs e)
{
string[] contens = new string[0];
string FileNameSql = "";
string templateFile = AppDomain.CurrentDomain.BaseDirectory;//程序⽂件⽬录
bool file_b = false;//默认txt⽂件不存在
if (Directory.Exists(templateFile))//若⽂件夹存在
{
FileNameSql= templateFile + "\\创建档案条⽬表.txt";
file_b = File.Exists(templateFile + "\\创建档案条⽬表.txt");//⽂件是否存在
if (file_b)
{
contens = File.ReadAllLines(templateFile + "\\创建档案条⽬表.txt");//存在读取这个txt
}
}
//获取到数据库连接信息
ExecuteCommand(GetSqlFile(FileNameSql, ""),DaoFactory.NewSJDao(Common.g_DataSource));
MessageBox.Show("创建案卷表和卷内表成功!");
}
/// <summary>
/// 读取⽂件并且修改
/
// </summary>
/// <param name="varFileName">⽂件路径</param>
/// <param name="dbname">数据库表名</param>
/// <returns></returns>
public  ArrayList GetSqlFile(string varFileName, string dbname)
{
ArrayList alSql = new ArrayList();
if (!File.Exists(varFileName))
{
return alSql;
}
StreamReader rs = new StreamReader(varFileName, System.Text.Encoding.Default);//注意编码
string commandText = "";
string varLine = "";
while (rs.Peek() > -1)
{
varLine = rs.ReadLine();
if (varLine == "")
{
continue;
}
if (varLine != "GO" && varLine != "go")
{
commandText += varLine;
commandText = commandText.Replace("@database_name=N'dbhr'", string.Format("@database_name=N'{0}'", dbname));                    commandText += "\r\n";
}
else
{
//将@ArchvTable和@ArchvFileTable替换成案卷表名和卷内表名
string pcom = "";
if(commandText.Contains("@ArchvTable")|| commandText.Contains("@ArchvFileTable"))
{
pcom= commandText.Replace("@ArchvTable", Common.g_QXPZAJ);
pcom = pcom.Replace("@ArchvFileTable", Common.g_QXPZJN);
}
alSql.Add(pcom);
commandText = "";
}
}
rs.Close();
return alSql;
}
sqltransaction什么意思/// <summary>
/// 连接数据库表并执⾏⽂件中的sql语句
/
// </summary>
/// <param name="varSqlList"></param>
/// <param name="connString"></param>
public static void ExecuteCommand(ArrayList varSqlList, string connString)        {
SqlConnection MyConnection = new SqlConnection(connString);
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();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。