For the code below I get the error
You have an error with your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name','Score') VALUES('cain','0') at line 1
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=bel.sunderland.ac.uk; " +
"database=bg30xw; " +
"uid=USERNAME; " +
"pwd=PASSWORD;";
string query = "INSERT INTO highscore('Name','Score') VALUES (#Name, #Score);";
using(MySqlConnection myconn = new MySqlConnection(connStr))
{
Console.WriteLine(query);
MySqlCommand insertCommand = new MySqlCommand(query,myconn);
insertCommand.Parameters.AddWithValue("#Name",sName);
insertCommand.Parameters.AddWithValue("#Score",iTotalScore);
try
{
myconn.Open();
insertCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
myconn.Close();
}
The error showed up in the 'messagebox.show(ex.message);' when I ran the program. I looked on google but most of the suggestions was for quotation marks, I have changed and re-changed them but to no avail.
Thanks
Use backticks to escape column (and table) names, not quotes
INSERT INTO highscore(`Name`,`Score`) VALUES (#Name, #Score)
Single-word column names don't need to be escaped (I don't think MySQL allows it, but I may be wrong);therefore, this should work:
INSERT INTO highscore(Name,Score) VALUES (#Name, #Score);
You may give an alias to a column, using spaces when you run a select statement, but I simply avoid them in general.
Related
The INSERT INTO statement contains the following unknown field name:
'NoName'. Make sure you have typed the name correctly, and try the
operation again.
That is the error thrown when I try to insert a record into a dbase file (.dbf) from a .Net app I am working on.
I use Oledb connection like this:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
I had similar issues while selecting. Some columns get returned as 'NoName' but still with data. I simply use the column index number in place of the column name.
Now I need to insert and it has been a block. Same error comes up with say (when you don't list out the column names):
INSERT INTO [tablename.dbf] VALUES (?, ?, ?);
Sample full code below:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
connection.Open();
OleDbTransaction trans = connection.BeginTransaction();
OleDbCommand command = new OleDbCommand(#"INSERT INTO [tablename.DBF]
VALUES
(
?, ?, ?
);", connection, trans);
command.Parameters.AddWithValue("param1", 7);
command.Parameters.AddWithValue("param2", "RCN");
command.Parameters.AddWithValue("param3", 0);
try
{
command.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
throw e;
}
finally
{
connection.Close();
}
I have seen forums discuss this when it happens in Ms Access. But nothing much so far on dbase. Been thinking it is a driver thing.
The dbase file was created by dbase plus (2007) application.
Don't use question marks in combination with named parameters, even #param1 etc. If you're inserting three values into this table, then name the parameters in the command text:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
connection.Open();
OleDbTransaction trans = connection.BeginTransaction();
OleDbCommand command = new OleDbCommand(#"INSERT INTO [tablename.DBF]
VALUES
(
#param1, #param2, #param3
);", connection, trans);
command.Parameters.AddWithValue("param1", 7);
command.Parameters.AddWithValue("param2", "RCN");
command.Parameters.AddWithValue("param3", 0);
try
{
command.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
throw e;
}
finally
{
connection.Close();
}
You are very close, but what you are probably failing on is the telling of WHICH columns you are inserting the values. Yes, OleDB uses "?" as place-holders for the parameters and they must match the same order as their corresponding needs of the SQL select, insert, update or delete. Add the explicit columns BEFORE the "Values" clause.
OleDbCommand command = new OleDbCommand(
#"INSERT INTO [tablename.DBF] ( tblColumn1, tblColumn2, tblColumn3 )
VALUES ( ?, ?, ? )", connection, trans);
THEN add your parameters in the specific order to match the command.
No need for the closing semi within the command statement as you only had one insert command anyhow.
The actual naming of the parameters as you had was ok for your own clarification, but the order of parameters is specifically correlated to the "?" place-holders in the insert statement.
I found out after a long time that this happened to tables with field-name longer than 8 or 9 characters. When its 10 or more characters long, the field name returns 'NoName'.
It sounds ridiculous.
When I made the field-name shorter this worked fine.
I got some insight into this here
Now with the fieldnames adjusted, my sample code above works perfectly.
I'm diving head first into both C# and Access databases. This is all brand new to me, so I have a small test database set up to work with a small template. I'm trying to figure out why I keep getting a syntax error that is triggered by the ExecuteNonQuery() method. Any help and insight would be appreciated.
Edit: SOLVED: This is the working code for this situation. All help was greatly appreciated!
public void addToDb()
{
String first = "John";
String last = "Doe";
String testPath = GVar.TEST_FILEPATH + GVar.TEST_DATABASE;
String strCommand = "INSERT INTO ID ([First], [Last]) Values(#First, #Last)";
OleDbConnection dbTest = null;
OleDbCommand cmd = null;
try
{
dbTest = new OleDbConnection(GVar.OLE_DB_WRITE + testPath);
dbTest.Open();
cmd = new OleDbCommand(strCommand, dbTest);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
Console.WriteLine("Data Added");
}
catch (Exception ex)
{
Console.WriteLine("Db Test: " + ex.Message);
}
dbTest.Close();
}
From OleDbCommand.Parameters property
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM
Customers WHERE CustomerID = ?
Therefore, the order in which
OleDbParameter objects are added to the OleDbParameterCollection must
directly correspond to the position of the question mark placeholder
for the parameter in the command text.
I don't see anything wrong in your INSERT statement other than this.
cmd.CommandText = "INSERT INTO Identity ([First],[Last]) VALUES(?, ?)";
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
I got a problem with my C#, whenever i try to save new data in the database coming from serial comm an error comes out and says
Incorrect Syntax Near '/'
I tried every suggestion everyone gave but it just wont stop..Here it is the piece of code where it comes out.
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SqlConnection cn = new SqlConnection(global::test_new.Properties.Settings.Default.Database3ConnectionString);
try
{
string sql = "INSERT INTO PowerData (Date/Time,Power(W)) values(" + this.powerTextBox.Text + ",'" + this.powerTextBox.Text + "'");
SqlCommand exeSql = new SqlCommand(sql, cn);
cn.Open();
exeSql.ExecuteNonQuery();
this.powerDataTableAdapter.Fill(this.database3DataSet.PowerData);
}
catch (Exception ex)
{
}
}
You need to escape special characters in table and column names like /
INSERT INTO PowerData ([Date/Time], Power(W)) values ...
In MySQL use backticks to escape, in MSSQL use brackets.
You've got some crazy column names there. If you want to include special characters in column names like that then you must wrap them in brackets in SQL, e.g. [Date/Time]. A better idea would be to not use such characters in the first place.
syntax should be like below, escape all columns with special characters
INSERT INTO PowerData
([Date/Time], [Power(W)])
VALUES
(GETDATE(), 'test1')
DEMO
First, "this.powerTextBox.Text" - I am guessing this shouldn't be the same value for both variables
change your code to this:
DateTime dt = DateTime.Parse(this.powerTextBox.Text);
string PowerW = this.powerTextBox.Text;
string sql = "INSERT INTO PowerData ([Date/Time],[Power(W)]) values(#val1, #val2);"
SqlCommand exeSql = new SqlCommand(sql, cn);
exeSql.Parameters.AddWithValue("#val1", dt);
exeSql.Parameters.AddWithValue("#val2", PowerW);
cn.Open();
exeSql.ExecuteNonQuery();
Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?
I've been working on a delete function for a while now, and I cannot get past this error.
Delete Failed ORA-00904 "SYSTEM"."DATA"."DATAROWVIEW": invalid identifier
private void button3_Click(object sender, EventArgs e)
{
string yesNoPrompt = "Are you sure you want to delete this patient?";
const string caption = "";
var result = MessageBox.Show(yesNoPrompt, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME =" + listBox1.SelectedItem.ToString() + ")" ;
try
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = new OracleCommand(sql, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
catch (System.Data.OracleClient.OracleException ex)
{
MessageBox.Show("Delete Failed" + ex.Message);
}
}
}
The table in the database is CLIENT and I am trying to find a specific person by their last name, or CLI_LNAME. I don't think the problem is in the name being passed, but more of how it is being passed.
Any ideas?
Your query gets translated to
DELETE FROM CLIENT WHERE (CLI_LNAME = SYSTEM.DATA.DATAROWVIEW)
Due to the missing single quotes and hence its trying to find a column named SYSTEM.DATA.DATAROWVIEW which is not present in the Client table. hence the error.
When you use single quotes then its looking for the text in that particular column
DELETE FROM CLIENT WHERE (CLI_LNAME = 'PatientName') // Now its not a column as such
Use Parameterized queries to avoid SQL injection
Looks like listBox1.SelectedItem.ToString() returns "SYSTEM"."DATA"."DATAROWVIEW". You probably want to access a specific item of the DataRowView that's the SelectedItem, not the entire DataRowView object itself. Maybe listBox1.SelectedItem[0].ToString() is what you want?.
Also you have to add quotes as #Habib.OSU mentions.
And the obligatory sql injection warning: Don't concatenate user inputs into SQL string. It opens up for SQL injection attacks. Use parameterized queries.
you are missing single quote in parameters
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME ='" + listBox1.SelectedItem.ToString() + "')" ;
Its better if you could use Parameterized query