I'd like to provide a command line interface to my db that allows the user to enter MULTIPLE database commands or queries (separated by line breaks in the textarea)
For each line, if its a query must return the results and if its a command, whether or not it was successful - thus allowing the user to paste a script into the text area and click 'GO' to have the batch executed.
I have been using a DataContext to interface with my database in the application but havent a CLUE where to start. Any assistance would be greatly appreciated
As the previous answer points out, please don't do this if it's a publicly accessible site!
If you must do it, the following code is close to what you're after - with a bit of modification you'll get exactly what you want.
public static bool ExecuteSql(string sqlScript)
{
bool success = true;
using (SqlConnection cn = new SqlConnection([YourConnectionString]))
{
SqlCommand cmd = null;
try
{
cn.Open();
string[] commands = sqlScript.Split(new string[] { "GO\r\n", "GO ", "GO\t" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string c in commands)
{
cmd = new SqlCommand(c, cn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
success = false;
throw new Exception("Failed to execute sql.", ex);
}
finally
{
cn.Close();
}
return success;
}
}