In Access Database Engine SQL code, when you need to specify that a literal value is of type DATETIME
, you can either explicitly cast the value to DATETIME
or use #
characters to delimit the value.
Using an explicit cast using the CDATE()
function:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', CDATE('2009-12-31 00:00:00'), 0);
Using a DATETIME
literal value:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', #2009-12-31 00:00:00#, 0);
When INSERT
ing a value into a column of type DATETIME
, if you do not specify an explicit DATETIME
value, the engine will implicitly attempt to coerce a value to DATETIME
. The literal value ‘test’ cannot be coerced to type DATETIME
and this would appear to be the source of your syntax error.
Note: none of the above applies to the NULL
value. In Access Database Engine SQL there is no way to cast the NULL
value to an explicit type e.g.
SELECT CDATE(NULL)
generates an error, «Invalid use of NULL». Therefore, to specify a NULL
DATETIME
literal, simply use the NULL
keyword.
It pays to remember that the Access Database Engine has but one temporal data type, being DATETIME
(its synonyms are DATE
, TIME
, DATETIME
, and TIMESTAMP
). Even if you don’t explicitly specify a time element, the resulting value will still have a time element, albeit an implicit one. Therefore, it is best to always be explicit and always include the time element when using DATETIME
literal values.
Проблема даже совсем непонятная. Вроде все правильно но выдает ошибку: Ошибка синтаксиса в инструкции INSERT INTO.
(База на MS Access)
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password='';Data Source=myFirma.mdb"); OleDbCommand myData = new OleDbCommand("select * from Users", myConnection); OleDbCommand myQuery = new OleDbCommand("insert into Users (name,surname,login,password,action)values('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "')",myConnection); myConnection.Open(); myQuery.ExecuteNonQuery(); myConnection.Close();
Попробовал другой вариант:
String myConn = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=myDataBase.mdb;"; String myQuery = "INSERT INTO Users ( name, surname, login, password, action) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "')"; OleDbConnection cn = new OleDbConnection(myConn); cn.Open(); OleDbCommand cmd = new OleDbCommand(myQuery, cn); cmd.ExecuteNonQuery(); cn.Close();
Кроме этих пробовал еще варианты, обыскал весь Гугл, ниче не помогло. Все время одна и та же ошибка на одной и той же строчке:
.ExecuteNonQuery();
Ошибка: Ошибка синтаксиса в инструкции INSERT INTO.
Последняя надежна на вас.
-
Перемещено
1 октября 2010 г. 22:40
MSDN Forums consolidation (От:Visual C#)
In Access Database Engine SQL code, when you need to specify that a literal value is of type DATETIME
, you can either explicitly cast the value to DATETIME
or use #
characters to delimit the value.
Using an explicit cast using the CDATE()
function:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', CDATE('2009-12-31 00:00:00'), 0);
Using a DATETIME
literal value:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', #2009-12-31 00:00:00#, 0);
When INSERT
ing a value into a column of type DATETIME
, if you do not specify an explicit DATETIME
value, the engine will implicitly attempt to coerce a value to DATETIME
. The literal value ‘test’ cannot be coerced to type DATETIME
and this would appear to be the source of your syntax error.
Note: none of the above applies to the NULL
value. In Access Database Engine SQL there is no way to cast the NULL
value to an explicit type e.g.
SELECT CDATE(NULL)
generates an error, «Invalid use of NULL». Therefore, to specify a NULL
DATETIME
literal, simply use the NULL
keyword.
It pays to remember that the Access Database Engine has but one temporal data type, being DATETIME
(its synonyms are DATE
, TIME
, DATETIME
, and TIMESTAMP
). Even if you don’t explicitly specify a time element, the resulting value will still have a time element, albeit an implicit one. Therefore, it is best to always be explicit and always include the time element when using DATETIME
literal values.
I keep getting an error when I attempt to insert values into a Access database.
The error is syntactic, which leads to the following exception:
OleDbException was unhandled Syntax error in INSERT INTO statement.
private OleDbConnection myCon;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\File.mdb");
}
private void insertuser_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
myCon.Open();
cmd.Connection = myCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO User ([UserID], [Forename], [Surname], " +
"[DateOfBirth], [TargetWeight], [TargetCalories], [Height]) " +
"VALUES ('" + userid.Text.ToString() + "' , '" +
fname.Text.ToString() + "' , '" +
sname.Text.ToString() + "' , '" +
dob.Text.ToString() + "' , '" +
tarweight.Text.ToString() + "' , '" +
tarcal.Text.ToString() + "' , '" +
height.Text.ToString() + "')";
cmd.ExecuteNonQuery();
myCon.Close();
}
Shin
6642 gold badges13 silver badges30 bronze badges
asked Jan 7, 2011 at 16:13
4
Well, you haven’t specified what the error is — but your first problem is that you’re inserting the data directly into the SQL statement. Don’t do that. You’re inviting SQL injection attacks.
Use a parameterized SQL statement instead. Once you’ve done that, if you still have problems, edit this question with the new code and say what the error is. The new code is likely to be clearer already, as there won’t be a huge concatenation involved, easily hiding something like a mismatched bracket.
EDIT: As mentioned in comments, Jet/ACE is vulnerable to fewer types of SQL injection attack, as it doesn’t permit DML. For this INSERT statement there may actually be no vulnerability — but for a SELECT with a WHERE clause written in a similar way, user input could circumvent some of the protections of the WHERE clause. I would strongly advise you to use parameterized queries as a matter of course:
- They mean you don’t have to escape user data
- They keep the data separate from the code
- You’ll have less to worry about if you ever move from Jet/ACE (whether moving this particular code, or just you personally starting to work on different databases)
- For other data types such as dates, you don’t need to do any work to get the data into a form appropriate for the database
(You also don’t need all the calls to ToString
. Not only would I expect that a property called Text
is already a string, but the fact that you’re using string concatenation means that string conversions will happen automatically anyway.)
answered Jan 7, 2011 at 16:15
Jon SkeetJon Skeet
1.4m868 gold badges9136 silver badges9198 bronze badges
13
I posted this as a comment to the duplicate question at: Syntax error in INSERT INTO statement in c# OleDb Exception cant spot the error
Put brackets [] around the table name
«User». It’s a reserved word in SQL
Server.
«User» is also a reserved word in Access (judging by the provider in your connection string).
But I completely agree with Jon—if you fix your current implementation, you are just opening up a big security hole (against your User table, no less!)
answered Jan 7, 2011 at 17:28
Tim M.Tim M.
53.7k14 gold badges121 silver badges163 bronze badges
This problem may occur if your database table contains column names that use Microsoft Jet 4.0 reserved words.
Change the column names in your database table so that you do not use Jet 4.0 reserved words.
answered Apr 23, 2014 at 11:43
1
If TargetWeight
, Height
, and TargetCalories
are floating-point or integer values, they don’t need to be surrounded by quotes in the SQL statement.
Also, not directly related to your question, but you should really consider using a parameterized query. Your code is very vulnerable to SQL injection.
answered Jan 7, 2011 at 19:13
Brennan VincentBrennan Vincent
10.8k9 gold badges32 silver badges54 bronze badges
public decimal codes(string subs)
{
decimal a = 0;
con_4code();
query = "select SUBJINTN.[SCODE] from SUBJINTN where SUBJINTN.[ABBR] = '" + subs.ToString() + "'";
cmd1 = new OleDbCommand(query, concode);
OleDbDataReader dr = cmd1.ExecuteReader();
here is error in dr it says syntax error ehile in DBMS its working Well
if (dr.Read())
{
a = dr.GetDecimal(0);
MessageBox.Show(a.ToString());
}
return a;
}
answered Mar 26, 2012 at 8:35
1
After this
cmd.CommandText="INSERT INTO User ([UserID], [Forename], [Surname], [DateOfBirth], [TargetWeight], [TargetCalories], [Height]) Values ('" + userid.Text.ToString() + "' , '" + fname.Text.ToString() + "' , '" + sname.Text.ToString() + "' , '" + dob.Text.ToString() + "' , '" + tarweight.Text.ToString() + "' , '" + tarcal.Text.ToString() + "' , '" + height.Text.ToString() + "')";
check what this contains, maybe [DateOfBirth]
has illegal format
answered May 12, 2013 at 7:34
CLARKCLARK
887 bronze badges
Recommended Answers
- is this compiling at all because there seems to be an extra d and s in the insertcommands under try.
if idnum is autonumber, primary key, you cannot insert it, you have to let access generate it for you.
if idnum is a foreing key and the value does …
Jump to Post
VALUES ('" & IDnum & "')"
inserts this as a string, where you defined it as a number in your table. Did you not get an error message from VB?
Good luck.
Jump to Post
Oussamah, you have been telling us that you had 2 tables that are related right. So does this relationship join orders.ordersid into customer.id? if that is the case, access would not let you insert a record where orders.orderid=9 if there is no customer with id=9. Don’t think that would produce …
Jump to Post
Sorry…. I will have a look at this tomorrow ok?
Jump to Post
OK. OrdresID is definitely in a 1 to many relationship with Customers.id. In access I was able to add a record in Orders with OrdersId = 9, but it needs a customer record with id 9.
The fact that Orderid is a combobox should not be a problem. But look …
Jump to Post
All 19 Replies
- is this compiling at all because there seems to be an extra d and s in the insertcommands under try.
-
if idnum is autonumber, primary key, you cannot insert it, you have to let access generate it for you.
-
if idnum is a foreing key and the value does not exist in the related master table then you are violating integrity.
It would help if you could let us have a look at the structure of you tables.
Good luck.
oussama_1
39
Posting Whiz in Training
- sorry my bad (its not the problom though :D)
- no its not autonumber or primary key its just a number
- the number already exist in the first table according to the relation
these are not the problem.. im going crazy over this
thank you PerplexedB
VALUES ('" & IDnum & "')"
inserts this as a string, where you defined it as a number in your table. Did you not get an error message from VB?
Good luck.
oussama_1
39
Posting Whiz in Training
i tried these statements :
"INSERT INTO Orders (OrdersID) VALUES ('" & IDnum & "')"
"INSERT INTO Orders (OrdersID) VALUES (" & IDnum & ")"
"INSERT INTO Orders ([OrdersID]) VALUES ('" & IDnum & "')"
"INSERT INTO Orders VALUES ('" & IDnum & "')"
"INSERT INTO Orders ([OrdersID]) VALUES (" & IDnum & ")"
Dim IDnum as Integer = 4
"INSERT INTO Orders (OrdersID) VALUES (" & IDnum & ")"
all with the same error message, Syntax error in INSERT INTO statement.
oussama_1
39
Posting Whiz in Training
Sorry i forgot to mention that OrdersID Column is a Combobox
Oussamah, you have been telling us that you had 2 tables that are related right. So does this relationship join orders.ordersid into customer.id? if that is the case, access would not let you insert a record where orders.orderid=9 if there is no customer with id=9. Don’t think that would produce a syntax error though.
Have debug.print the sql string. Often that exposes syntax errors.
Alternatively, would you show is the insert statement that does work for you?
Good luck my friend.
Edited
by PerplexedB because:
typos
oussama_1
39
Posting Whiz in Training
yes you are right about the relation but none of the codes works for me.
say there’s a customer with ID = 1 and i would try the code above or any of the codes to insert the number 1 into ordersID still wont work
i think it got something to do with the fact its a combobox am i right ?
thank for your help
oussama_1
39
Posting Whiz in Training
ok Here’s the access file
Dropbox.com
user oussama.j.zeidan@gmail.com
pass 123456
Sorry…. I will have a look at this tomorrow ok?
oussama_1
39
Posting Whiz in Training
OK. OrdresID is definitely in a 1 to many relationship with Customers.id. In access I was able to add a record in Orders with OrdersId = 9, but it needs a customer record with id 9.
The fact that Orderid is a combobox should not be a problem. But look at it, it will not allow you to enter values under 9!
You should
-
open your customers table and look at what id’s are available in it. If there are none, you should add a record and take a note of which id is generated.
-
execute
Dim IDnum as Integer = <any value of customer id>
«INSERT INTO Orders (OrdersID) VALUES (» & IDnum & «)»
Good luck.
Edited
by PerplexedB
oussama_1
39
Posting Whiz in Training
wont work
you have the file so please try this code :
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source='" & yourlocation\InvoiceProgram.accdb & "';" & "Persist Security Info=False;" & "Jet OLEDB:Database Password=" & ";")
' the record already exist in customers with the ID 9
Dim IDnum As String = "9"
Dim insertCommands As New OleDb.OleDbCommand("INSERT INTO Orders (OrdersID) VALUES (" & IDnum & ")", Connection)
Try
Connection.Open()
insertCommands.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
Finally
Connection.Close()
End Try
and tell me why it wont work
thank you
Do you have customer 9 now? In the file that you sent me there wasn’t.
oussama_1
39
Posting Whiz in Training
there is 9 check it
oussama_1
39
Posting Whiz in Training
ossamah, have you succeeded in entering a record in access? It worked for me.
This worked for me on your original .accdb. :
Module Module1
Sub Main()
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=t:\_recent\130922 oussama\InvoiceProgram.accdb;Persist Security Info=False;" & "Jet OLEDB:Database Password=" & ";")
' the record already exist in customers with the ID 9
Dim IDnum As String = "9"
Dim insertCommands As New OleDb.OleDbCommand("INSERT INTO Orders (OrdersID) VALUES (" & IDnum & ")", Connection)
Try
Connection.Open()
insertCommands.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message & " - " & ex.Source)
Finally
Connection.Close()
End Try
End Sub
End Module
My previous answers were based on a state of the your .accdb after I had somewhat played around with it.
Maybe you should try your program on the .accdb as you sent it to me?
I dropped my version back. Hope that will help you find out your problem.
Good luck.
Edited
by PerplexedB because:
completing answer
oussama_1
39
Posting Whiz in Training
so we did the same thing but it only worked for you
ill check my access file in dropbox tomorrow
10x PerplexedB
oussama_1
39
Posting Whiz in Training
my code works!
this was the problem
my access file needed some query fixes
thanks PerplexedB for your time
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.