C # Read the *. SQL file and execute the SQL statement

Source: Internet
Author: User
Idea: Read the file first, use GO as the Section, and use each GO Section as an SQL command to execute it together through transactions.

Public static 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); // pay attention to Encoding
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
{
AlSql. Add (commandText );
CommandText = "";
}
}

Rs. Close ();
Return alSql;
}

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.