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
Related
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();
So I'm receiving this problem, I tried everything. Kinda stuck
My access database design:
ID - AutoNumber
Data - ShortText
And the insert command:
OleDbCommand command = new OleDbCommand();
string sql = "INSERT INTO Table (Data) VALUES (#Data)";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.AddWithValue("#Data", "Test");
connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex);
throw;
}
connection.Close();
This might be dumb but I'm really lost and I have no idea what to do.
The TABLE is a reserved keyword so you should change it's name or you should enclose it in square brackets like [Table]:
string sql = "INSERT INTO [Table] (Data) VALUES (#Data)";
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.
As our question got closed yesterday, we unfortunately have to open a new one. So here goes.
This is the old question: MySQL connection with C# through PHPMyAdmin created database
Firstly, thanks for all the answers! So we have implemented Rahul and ActiveHigh's answers and updated the code. Furthermore, we have added a way to check if the connection is a success or not. Now when we try to insert data we get the error message from the catch. The test location is still the same. Here is an image of the table in the database: https://www.dropbox.com/s/g2c70ty9qb1h7bw/ScreenshotDatabase.png
Anyone have any idea what is going wrong or an idea how to debug it?
(We have checked inside phpmyadmin whether or not the table is empty with a SQL query. It is empty.
protected void Button1_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection connection;
string server = "db.cce-solutions.dk";
string database = "web626445";
string uid = "******";
string password = "******";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
DisplayMessage.Text = "Data entered succesfully.";
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
cmd.Parameters.AddWithValue("#Name", YourName.Text);
cmd.Parameters.AddWithValue("#Email", YourEmail.Text);
cmd.Parameters.AddWithValue("#Telephone", YourPhone.Text);
cmd.Parameters.AddWithValue("#Category", Category.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Date", "test");
cmd.Parameters.AddWithValue("#Description", Description.Text);
cmd.ExecuteNonQuery();
}
else
{
DisplayMessage.Text = "Database connection failed.";
}
}
catch (Exception ex)
{
DisplayMessage.Text = "Error occured. Please try again later.";
}
connection.Close();
We found out we had assigned erroneous column names. In the insert statement we wrote yourName, yourEmail and so on (as you can see below) which needed to be changed to Name, Email, and so on.
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
Furthermore we removed the if loop since we did not need it and added a throw to the catch to get more detailed feedback. Hope this can help anyone stuck in the same problem.
Don't be us - check your column names! ;)
I tried some of your suggestions but still the same 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 ''' (size int(5))' at line 1
Here is my code:
try{
query = "CREATE TABLE #name (size int(5))";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = txtboxName.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
i think you intended to use backticks `` to escape table name but used single quotes instead.
query = "CREATE TABLE `"+ txtboxName.Text + "`(size int(5))";
I would try to add escape sequences to txtboxName.Text. There can be some special characters, that break your SQL statement.
You missed space between table name and the column definitions
query = "CREATE TABLE "+ txtboxName.Text + " (size int(5))";
|
put space here
sql injection... don't use inline parameters. below is sample code with few best practices what I know. But you can't use parameters for table names.
public void CreateTable(string tblName)
{
using (var con = new MySqlConnection(MySqlConnectionString))
{
using (var cmd = new MySqlCommand(String.Format("CREATE TABLE {0} (size int(5))",tblName), con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}