Executing sql file with multiple statements - c#

I'm wanting to execute a bunch of sql files and I'm having problems with (i think) files that have multiple statements in them. See here:
http://pastebin.com/yenknuq6
Trying to execute this sql throws this exception:
"at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior
behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()"
I'm using MySql connectors and I'm not doing any modification to the strings and just reading them from file.
using (MySqlConnection conn = new MySqlConnection())
{
try
{
conn.ConnectionString = connect_str;
conn.Open();
Console.WriteLine("\n[EXECUTING] " + file);
String sql = File.ReadAllText(file);
if (sql != null && !sql.Equals(""))
{
Debug.WriteLine(sql);
MySqlCommand command = new MySqlCommand(sql, conn);
command.CommandText = sql;
command.Prepare();
command.ExecuteNonQuery();
}
else
Console.WriteLine("no sql");
conn.Close();
}
catch (Exception e)
{
Console.WriteLine("[SQL EXCEPTION] " + e.StackTrace);
}
}

You must enter connection parameter Allow User Variables=True to make it work.

Related

Connection Timeout SQL c#

I have a project and when I try to run it and the data test is big I have always a connection timeout.
I added "sqlCmd.CommandTimeout = 3600;" but still not working.
What could am I doing wrong?
This is my code:
public void createCode(String ce, int ord, String beh, int wkd)
{
String strSql = "";
SqlCommand sqlCmd;
SqlConnection conexion = new SqlConnection(getConexion());
try
{
if (conexion.State != ConnectionState.Open)
conexion.Open();
//The insert works fine in sql server
strSql = "Insert into x with values";
sqlCmd = new SqlCommand(strSql, conexion);
sqlCmd.CommandTimeout = 3600;
sqlCmd.ExecuteScalar();
}
catch (Exception ex)
{
throw new Exception("Error creating Code. " + ex.Message);
}
finally
{
if (conexion.State == ConnectionState.Open)
conexion.Close();
}
}
You might need to set transaction timeout in your config file, like so;
<system.transactions>
<defaultSettings timeout="01:00:00" />
</system.transactions>
sqlCmd.ExecuteScalar() is not correct for your script, try using sqlCmd.ExecuteNonQuery() instead and remove timeout.
sqlCmd = new SqlCommand(strSql, conexion);
sqlCmd.ExecuteNonQuery();
Check each function, ExecuteScalar tries to return first value from a select, while ExecuteNonQuery does not retrieve any value, just gets num of rows affected.
Hope it helps!

C# MySQL Syntax error in SQL Statement

I have this simple method that is supposed to insert a row into a DB. It is throwing an exception.
private void AddToLiveQueue(int user_id, bool release = false)
{
string sql = "INSERT INTO live_support_queues (user_id, release, created_at, updated_at)";
sql += " VALUES(?user_id, ?release, ?created_at, ?created_at)";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?user_id", user_id);
cmd.Parameters.AddWithValue("?release", release);
cmd.Parameters.AddWithValue("?created_at", DateTime.UtcNow);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
SendEmail email = new SendEmail();
email.Send(ex.Message + " " + ex.ToString());
}
}
I am getting this error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release, created_at, updated_at) VALUES(70, 0, '2017-09-22 23:00:16.686741', '20' at line 1"
Any help is greatly appreciated. Thanks!
release is a reserved word, and needs escaped with ` symbols if used as an identifier.
https://dev.mysql.com/doc/refman/5.7/en/keywords.html

How to insert data into MySQL database using Asp.net

I am trying to insert data into MYSQL database using Asp.Net but I am getting the following error message: Failed to connect to the database due to System.InvalidOperationsException.The connection must be valid and open.
Here is what I am doing:
protected void SU_Button_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=mno; Database=xyz; User ID=abc; Password=abc";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
string insertData = "insert into signup_table(firstname,surname,mobile_number,email_address,password," +
"confirm_password) values (#F_Name, #S_Name, #M_Number, #E_Address, #Password, #C_Password)";
MySqlCommand command = new MySqlCommand(insertData, connection);
command.Parameters.AddWithValue("#F_Name",FN_TextBox.Text);
command.Parameters.AddWithValue("#S_Name", SN_TextBox.Text);
command.Parameters.AddWithValue("#M_Number", MN_TextBox.Text);
command.Parameters.AddWithValue("#E_Address", EA_TextBox.Text);
command.Parameters.AddWithValue("#Password", P_TextBox.Text);
command.Parameters.AddWithValue("#C_Password", CP_TextBox.Text);
int result = command.ExecuteNonQuery();
connection.Open();
MessageBox.Show("Connected to database");
MessageBox.Show("Data inserted successfully");
}
catch(Exception ex)
{
MessageBox.Show("Failed to connect to database due to" + ex.ToString());
MessageBox.Show("Failed to insert data due to" + ex.ToString());
}
}
}
Please suggest something. Thanks in advance... :)
You have to open your connection before you execute the query.
connection.Open();
int result = command.ExecuteNonQuery();
also dont forget to close your connecion after you finished.
change this
int result = command.ExecuteNonQuery();
connection.Open();
to this
connection.Open();
int result = command.ExecuteNonQuery();

SQL delete command?

I am having trouble with a simple DELETE statement in SQL with unexpected results , it seems to add the word to the list??. Must be something silly!. but i cannot see it , tried it a few different ways. All the same result so quite confused.
public void IncludeWord(string word)
{
// Add selected word to exclude list
SqlConnection conn = new SqlConnection();
String ConnectionString = "Data Source = dev\\SQLEXPRESS ;" + "Initial Catalog=sml;" + "User id=** ;" + "Password =*;" + "Trusted_Connection=No";
using (SqlConnection sc = new SqlConnection(ConnectionString))
{
try
{
sc.Open();
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
Command.Parameters.AddWithValue("#word", word);
Command.ExecuteNonQuery();
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
finally
{
sc.Close();
}
ExcludeTxtbox.Text = "";
Box.Text = " Word : " + word + " has been removed from the Exclude List";
ExcludeLstBox.AppendDataBoundItems = false;
ExcludeLstBox.DataBind();
}
Try removing the single quotes. Also why are you concatenating your SQL string with a connection object (.. word='#word'" + conn)???
Try like this:
try
{
using (var sc = new SqlConnection(ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM excludes WHERE word = #word";
cmd.Parameters.AddWithValue("#word", word);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
...
Notice also that because the connection is wrapped in a using block you don't need to Close it in a finally statement. The Dispose method will automatically call the .Close method which will return the connection to the ADO.NET connection pool so that it can be reused.
Another remark is that this IncludeWord method does far to many things. It sends SQL queries to delete records, it updates some textboxes on the GUI and it binds some lists => methods like this should be split in separate so that each method has its own specific responsibility. Otherwise this code is simply a nightmare in terms of maintenance. I would very strongly recommend you to write methods that do only a single specific task, otherwise the code quickly becomes a complete mess.
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
should be replaced with
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'",
conn);
Also try by removing single quotes as suggested by others like this
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word=#word",
conn);
The #Word should not be in quotes in the sql query.
Not sure why you're trying to add the connection on the end of the sql query either.
To debug this, examine the CommandText on the SqlCommand object. Before reading further, you should try this.
The issue comes with adding the single quotes around a string that is parameterized. Remove the single quotes and life is beautiful. :-)
Oh, and your conn is an object and needs a comma, not a +.
See the code below:
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM supplier";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
See the code below:
String queryForUpdateCustomer = "UPDATE customer SET cbalance=#txtcustomerblnc WHERE cname='" + searchLookUpEdit1.Text + "'";
try
{
using (SqlCommand command = new SqlCommand(queryForUpdateCustomer, con))
{
command.Parameters.AddWithValue("#txtcustomerblnc", txtcustomerblnc.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record Update of Customer...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
You can also try the following if you don't have access to some of the functionality prescribed above (due, I believe, to older versions of software):
using (var connection = _sqlDbContext.CreatSqlConnection())
{
using (var sqlCommand = _sqlDbContext.CreateSqlCommand())
{
sqlCommand.Connection = connection;
sqlCommand.CommandText = $"DELETE FROM excludes WHERE word = #word";
sqlCommand.Parameters.Add(
_sqlDbContext.CreateParameterWithValue(sqlCommand, "#word", word));
connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
...
I'm an associate dev. Hence the "I believe" above.

Inserting into an MySQL db using 1 connection (C#.NET)

i'm having an issue using C# inserting multiple rows into a MySQL database, have the following code;
//Upload to mysql
string connStr = "server=server;user=username;database=databasae;port=3306;password=password;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
foreach (Channel chan in results)
{
// Perform databse operations
try
{
//Create sql statment with parameters
string sql = "INSERT INTO channels(ID, Name) VALUES (#id,#name)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#id", chan.ID);
cmd.Parameters.AddWithValue("#name", chan.Name);
cmd.ExecuteNonQuery();
updateStatus("Inserted");
}
catch (Exception ex)
{
updateStatus(ex.Message.ToString());
}
conn.Close();
I seem to be getting "connection must be valid and open". From what i can see i'm passing the connection string correctly and i'm using ExecuteNonQuery. And idea's?
thanks
conn.Close(); should be outside the foreach.
The following would work :
//Upload to mysql
string connStr = "server=server;user=username;database=databasae;port=3306;password=password;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
foreach (Channel chan in results)
{
// Perform databse operations
try
{
//Create sql statment with parameters
string sql = "INSERT INTO channels(ID, Name) VALUES (#id,#name)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#id", chan.ID);
cmd.Parameters.AddWithValue("#name", chan.Name);
cmd.ExecuteNonQuery();
updateStatus("Inserted");
}
catch (Exception ex)
{
updateStatus(ex.Message.ToString());
}
}
conn.Close();
Looks like the connection is inside the foreach loop. It should be outside the foreach loop.
conn.Close(); should be outside the foreach loop.
How about using
using(MySqlConnection conn = new MySqlConnection(connStr))
{
//your stuff in here
}
This is transformed into a try final block .. so should take care of your connection woes.
add finally block to the try catch code and put conn.close() in it.like
finally
{
if(conn.ConnectionSTate=Connectionstate.open)
{
conn.close()
}
}

Categories

Resources