I have an insert statement
command.CommandText = " insert into system (ziel, comment, status,art) values (#eort,#comment,#statebox,#Eart) ";
Behind statebox is a Combobox. Every word which can be chosen in the Combobox is created as a tablerow in my database.
the values are created here:
command.Parameters.AddWithValue("#eort",textBo3x.Text);
command.Parameters.AddWithValue("#comment", textBox_Copy1.Text);
command.Parameters.AddWithValue("#statebox", MyComboBox.Text);
command.Parameters.AddWithValue("#Eart", MyComboBox_Copy1.Text);
command.Parameters.AddWithValue("#thetime", thetime_insert.Text);
This works.
But I want to use the #values in the insert Statement like this:
command.CommandText = " insert into els (ziel, #statebox,comment,status,Eart) values (#eort,#thetime,#comment,#statebox,#Eart) ";
This gives me an mysql error.
It seems that the #values have '' at the words.
How can i delete this?
Your INSERT statement as pointed below is wrong. You can't simply plug-in a dynamic column in your insert statement which doesn't exists in your table schema
insert into system (ziel, #statebox,comment,status,Eart)
This can only be done in case of SELECT statement and doing below is perfectly alright
select ziel, #statebox,comment,status,Eart from `system`
Well, if you have your column name in variable then build your query string like
string query = string.Format("insert into els (ziel, {0},comment,status,Eart) values ", column_name_variable);
You cannot use a parameter to reference a field name. However, if you provide your user with a predetermined list of fields between he/she can choose then you can safely use a form of string concatenation to insert the field to update/insert into.
This means that you need to have a combobox without any editing capability but just a selection of the possible fields.
In your case, it seems that this combobox could be the one named MyComboBox
Thus
command.CommandText = #"insert into els
(ziel, " + MyComboBox.SelectedItem.ToString() +
#",comment,status,Eart) values
(#eort,#thetime,#comment,#statebox,#Eart)";
Said that consider to remove the use of AddWithValue. This shortcuts has big drawbacks, in particular when you pass a string variable (Text) and expects it to correctly translate your text in a datetime value.
Use the Add method instead converting and checking your inputs and specifying the correct datetype for the parameter.
DateTime dt;
if(!DateTime.TryParse(thetime_insert.Text, out dt);
// Message, not a valid date....
else
command.Parameters.Add("#thetime", MySqlDbType.Date).Value = dt;
Related
I need to add column to table, for now I have this code:
public void InsertParameter(string ColumnName)
{
string sql = "ALTER TABLE table_name ADD :value1";
SQLiteCommand cmd = new SQLiteCommand(sql,conn);
cmd.Parameters.AddWithValue("value1", ColumnName);
cmd.ExecuteNonQuery();
}
But this give me syntax error:
near ":value1":syntax error
I really can't figure out what is wrong with this query?
The reason it doesn't work is that the syntax for SQLite's ALTER TABLE statement requires a column-name here instead of an arbitrary string-typed expr. This means you can't use a bind-parameter with it.
(Apparently, the implementation of prepared statements requires the table and column names to be known at “compile” time, so it can't be a variable.)
If you need a C# function that dynamically selects a column name at runtime, you need to dynamically create the SQL statement with a hard-coded column name. (Use double-quoting to prevent SQL injection attacks.)
string sql = "Alter Table table_name ADD "\"" + ColumnName.Replace("\"", "\"\"") + "\"";
I am trying to execute following code for I have hardcoded the date in but it doesn't seem to delete it before I had data mismatch expection.
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
I ran the SQL query in Access and it didn't work. So I generated it using the tools avaliable there and it looks like that:
DELETE Class.ClassDate FROM Class WHERE (((Class.ClassDate)=#12/10/2015#));
Instead of:
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
use
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#";
Be sure not to put ; before " in Access SQL in C#
A good reality check is to replace DELETE with SELECT *, if the WHERE clause doesn't return any rows in a SELECT query, it isn't going to delete any either.
Is it possible there is a time component stored in the field Date? The value #10/12/2015# is implicitly #10/12/2015 12:00 AM#, and a test for equality will only return rows that match exactly. If you're actually looking for all rows with any time of day on that date...
WHERE [Date] BETWEEN #10/12/2015# AND #10/12/2015 11:59 PM#
(Not sure if Date is a reserved word in Access -- life is too short to depend on Jet -- but even if it isn't the square brackets won't hurt anything.)
I Try to insert to MySQL database in C#, but what i got is 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 "insert (NoNota, Nama, Tanggal, Tipe, Keterangan) VALUES ('1111',
'Kickass', '201" at line 1
i think the problem is the DateTime, in my database datatype i set it to DATETIME, Here is my code
string sqlQuery;
sqlQuery = "INSERT INTO insert (id, Name, Date, Type, Notes) VALUES ('1111', 'Kickass', '2013-09-09', 'Cash', 'Nothing')";
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(sqlQuery, connect);
cmd.ExecuteNonQuery();
CloseConnection();
MessageBox.Show("Operation INSERT is SUCCESS!!");
}
What's wrong with it? i try excute my SQL Queries it work very FINE in MySQL Workbench, it automatically convert the DateTime and insert it into the table. Any clue?
insert is a reserved word (INSERT INTO insert). Rename the table or escape with backticks. I'd highly recommend renaming.
You need to escape reserved words in MySQL like INSERT with backticks
INSERT INTO `insert` (id, Name, ...
^------^---------------------here
But it would be way better to rename your table. insert does not say anything about your data. Try to think of its content. When you have hundreds of tables in a database you need to name every one very carefully to keep track what it contains.
When you name your column, name it after the single word that finishes this sentance:
The data of my table holds ...
I want to insert a date record to an Access database. Here is my code:
cmd.CommandText = "INSERT INTO AlarmHistory(Date) VALUES ('6/8/2012')";
cmd.ExecuteNonQuery();
It gives Syntax error in INSERT INTO statement. error at second row.
The screenshot that show my cell data type on db is below.
Use parameters
cmd.CommandText = "INSERT INTO AlarmHistory([Date]) VALUES (?)";
cmd.Parameters.AddWithValue("#date", new DateTime(2012,06,8));
cmd.ExecuteNonQuery();
This will preserve your code from SqlInjection and you could stop to worry about quoting your values-
Just tried creating a dummy database. It's the Date Field. You should enclose in square brackets because Date is a reserved keyword
Here the list of the reserved keywords for Jet 4.0
Perhaps date is a reserved word. If so, it should be delimited (maybe with brackets):
INSERT INTO AlarmHistory([Date]) VALUES ('6/8/2012')
Try use
"INSERT INTO AlarmHistory(Date) VALUES ('#6/8/2012#')"
You should add a # sign around the date that should solve your problem.
please remember before creating database table avoid to give fields names DATE and NAME
it will throws error while inserting. eg..give field password ,date instead of give like that ,password_user ,bill_date
Note:date and password not acceptable field name in MS Access table .bcoz it is a keywords.
IT SHOULD SOLVE YOUR PROBLEM
Thanks.
Rathina.
I have a problem with this:
String or binary data would be truncated
And this is my coding:
String savePath = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile\" + fileName;
inputImageBox.Image = Image.FromFile(ImageLocation);
inputImageBox.Image.Save(savePath);
String sqlData = "INSERT INTO CharacterOCR(ImageName, ImagePath, Character, CharacterDescription)
VALUES('"+fileName+"', '"+savePath+"', '"+typeName+"', '"+CharDesc+"')";
SqlCommand cmd = new SqlCommand(sqlData, con);
cmd.ExecuteNonQuery(); // <<<<<error indicates here
What is the problem?
Look at the schema of your table and look at the max lengths. You're probably trying to insert something larger than the max length.
That just means that one of the values you're trying to cram into a column is too long for the data type you've defined for that column.
For example, trying to INSERT "Hello" to a column that's only a VARCHAR(4).
It's generally considered better coding practice to store the paths to where your images are in your database, while keeping your images stashed in the appropriate directory structure.
If you're set on inserting image data into a database, kindly let everyone know what version your database is.
EDIT:
Pull up your SQL Schema for the ImagePath column, and tell me how many characters you have it defined to accept.
Next, before you execute your SQL, call Console.WriteLine(savePath.Length).
Is savePath.Length greater than your ImagePath column definition?
You will get this error, when the column length is different when compared with the table definition and storedprocedure parameter.
Example:
I have a table called
Employee
with a column Reason
and while declaring the table the column length for Reasonis varchar(100)
and while writing a stored procedure for the Employee table i am declaring Reason parameter as #Reason varchar(250).
In this situation you will be getting this error.
So make sure that the column length is unique.