Wednesday, May 16, 2012

how to execute sql query in c sharp

Here i will show how to Excute the sql query in sql server using c#. For this I will use one method with two parameters which are database connection string and file name.Then read the text in file and passed to string array.Finally we will execute the query using sqlcommand

public void executeSqlfileincsharp(string connectionStringName, string executesqlFileName)
  {
string sqlConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
FileInfo file = new FileInfo(executesqlFileName);
string sqlString = file.OpenText().ReadToEnd();
using (SqlConnection mySqlConnection = new SqlConnection(sqlConnectionString))
{
string[] spliter = { Environment.NewLine, " GO ", Environment.NewLine };
string[] sqlArrayString = sqlString.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
string executeString = "";
for (int i = 0; i < sqlArrayString.Length; i++)
    {
  executeString = executeString + " " + sqlArrayString[i].ToString();
 }
using (SqlCommand mySqlCommand = mySqlConnection.CreateCommand())
{
 mySqlCommand.CommandText = executeString;
 mySqlConnection.Open();
 mySqlCommand.ExecuteNonQuery();
}
}
}

No comments:

Bel