Syntax error in number in query expression

I'm using a MS Access database. I want to get first and last records that are in between 2 dates. But I get error when using a BETWEEN operator: Syntax error in number in query expression 'Datum_k

I’m using a MS Access database. I want to get first and last records that are in between 2 dates. But I get error when using a BETWEEN operator:

Syntax error in number in query expression ‘Datum_k BETWEEN 3.4.2017. AND 3.4.2017.’.

My code:

private void GetPrviZadnjiBrojRacuna()
{
    OleDbCommand commandOD = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE (Datum_k BETWEEN " + datumOd + " AND " + datumDo + ") ORDER BY [Datum_k] ASC", dataModel.CS);
    OleDbCommand commandDO = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE [Datum_k] >= " + datumOd + " AND [Datum_k] <= " + datumDo + " ORDER BY [Datum_k] DESC", dataModel.CS);

    try
    {
        dataModel.DT.Clear();
        OleDbDataAdapter ODbDA = new OleDbDataAdapter(commandOD);

        if (!dataModel.CS.State.Equals(ConnectionState.Open))
        {
            dataModel.CS.Open();
        }

        // GET OD 
        ODbDA.Fill(dataModel.DT);
        odRacuna = dataModel.DT.Rows[0].ToString();

        // GET DO
        ODbDA.SelectCommand = commandDO; 
        dataModel.DT.Clear();
        ODbDA.Fill(dataModel.DT);

        doRacuna = dataModel.DT.Rows[0].ToString();

        dataModel.CS.Close();
        dataModel.DataLoaded = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

marc_s's user avatar

marc_s

722k173 gold badges1320 silver badges1443 bronze badges

asked Apr 3, 2017 at 11:48

solujic's user avatar

4

Addressing two issues with your code snippet:

  • You should never use string interpolation to build a query. This lends itself to SQL injection. Many, many topics surrounding this. I suggest you read up.
  • You have missed the ' single quotes around your date strings.

Using parameterised queries, you can kill two birds with one stone:

OleDbCommand commandOD = new OleDbCommand(@"
    SELECT Dokument
    FROM DnevniPromet
    WHERE (Datum_k BETWEEN @datumOd AND @datumDo)
    ORDER BY [Datum_k] ASC", dataModel.CS);

commandOD.Parameters.AddRange(new OleDbParameter[]
{
    new OleDbParameter("@datumOd", datumOd),
    new OleDbParameter("@datumDo", datumDo)
});

solujic's user avatar

solujic

8851 gold badge16 silver badges40 bronze badges

answered Apr 3, 2017 at 11:57

Chris Pickford's user avatar

Chris PickfordChris Pickford

8,5265 gold badges47 silver badges72 bronze badges

2

  • Home
  • VBForums
  • Visual Basic
  • Database Development
  • syntax error in number in query expression number and date in vb6

  1. Aug 21st, 2018, 09:28 AM


    #1

    siadli is offline

    Thread Starter


    New Member


    syntax error in number in query expression number and date in vb6

    Sorry to come back to you but I still have not resolved my concern DAO vB6. but the command line works in VB5 why I do not know …… If a person has an idea here is an image and some of the code otherwise I leave you a link from the program file and the database data that does not work. Otherwise if you do not arrive in ADO do it in recent ADO data control.

    here is the code that works in VB5. stating that c is the date giving the error for VB6
    [CODE]
    DataHisto.DatabaseName = App.Path & » technique.mdb»
    DataHisto.RecordSource = «select * from histo where number =» & Val (LblNumCar) & «and date =» & Format (ListDateh) & «»
    DataHisto.Refresh
    [/ CODE]

    Name:  Capture.jpg
Views: 1601
Size:  40.1 KB

    i also tried this:

    [CODE]
    Data1.RecordSource = «select * from histo where number =» & Val (LblNumber) & «and date = #» & Format (ListDateh) & «#»
    ‘or
    DataHisto.RecordSource = «select * from histo where date = #» & Format (ListDateh, «dd.mm.yyyy») & «#»
    ‘or
    DataHisto.RecordSource = «SELECT * FROM histo WHERE number =» _
    & Val (LblNumber) _
    & «AND date = #» _
    & Str $ (CDate (ListDateh)) _
    & «#»
    [/ CODE]

    always had the same error code 3075

    For those who want to have the form and test data here is the link:

    https://github.com/siadli/histo

    or ZIP.

    technique.zip

    «For those interested in the car repair management project for a full garage I can provide it»
    Thank you for your help and experience that I have unfortunately …..

    Last edited by siadli; Aug 27th, 2018 at 03:00 PM.

    Reason: rajout d un lien du projet en question


  2. Aug 21st, 2018, 10:24 AM


    #2

    Re: syntax error in number in query expression number and date in vb6

    Your DATE needs to be in quotes (if MS SQL) — maybe #’s if ACCESS.

    Using VAL() to turn a string into a number to then concatenate that «value» into a string is just silly. It is a «number» in the query because it is NOT IN QUOTES in that final query string.

    If this is MS SQL get the query to work in a QUERY WINDOW in Management Studio and then code logic that makes that EXACT SAME string,


  3. Aug 21st, 2018, 10:49 AM


    #3

    Re: syntax error in number in query expression number and date in vb6

    put # around the date

    Code:

    Data1.RecordSource = "select * from histo where num�ro=" & Val(LblNum�ro) & " and date = #" & Format(ListeDate) & "#"


  4. Aug 21st, 2018, 10:53 AM


    #4

    Re: syntax error in number in query expression number and date in vb6

    and we’re back again at using Parameters…..

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  5. Aug 21st, 2018, 10:58 AM


    #5

    Re: syntax error in number in query expression number and date in vb6

    Zvoni — I wondered about that… can you use parameters on the RecordSource of a DataControl? Something tells me no, but I’ve never used the DataControl beyond some experimenting quite sometime ago, so I don’t really know.

    -tg


  6. Aug 21st, 2018, 11:10 AM


    #6

    Re: syntax error in number in query expression number and date in vb6

    What does parameters have to do with this question?

    If the OP is unclear on quotes around dates and simple query syntax, then that lesson needs to be given. Session 2 would be parameters. If you skip lesson 1 you are NOT building a future coder at all!


  7. Aug 21st, 2018, 11:36 AM


    #7

    Re: syntax error in number in query expression number and date in vb6

    Date and time literals in Jet SQL are delimited by «#» symbols but are formatted for the invariant locale (i.e. Earth Standard which is basically U.S. English).

    But you’d be far better off using a parameter query instead of cobbling together SQL text dynamically anyway. Then you don’t have to format such values as text… just to have the database turn around and parse it back into live data to use it.


  8. Aug 21st, 2018, 04:09 PM


    #8

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Bonsoir et merci de votre aide mais �a me donne toujours la m�me erreur et c est bien sur la date qui donne l erreur

    Last edited by siadli; Aug 21st, 2018 at 04:18 PM.


  9. Aug 21st, 2018, 04:14 PM


    #9

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Bonsoir et merci de votre r�ponse si je comprends bien il faut 2 requ�tes au lieu de regroup� les requ�te mais je pense que ce la requ�te de la date qui donne cette erreur m�me en d�limitant par des symboles «#»


  10. Aug 21st, 2018, 06:24 PM


    #10

    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by techgnome
    View Post

    Zvoni — I wondered about that… can you use parameters on the RecordSource of a DataControl? Something tells me no, but I’ve never used the DataControl beyond some experimenting quite sometime ago, so I don’t really know.

    -tg

    No idea, since i never used any of those controls in my life

    What does parameters have to do with this question?

    If the OP is unclear on quotes around dates and simple query syntax, then that lesson needs to be given. Session 2 would be parameters. If you skip lesson 1 you are NOT building a future coder at all!

    szlamany,

    in that case this begs the question, why in blazes he’s even starting to code a UI, if he hasn’t even the basics for a database down.
    Every DB-Design-Tool i know of has at least an option to fire some queries against your Database to check if the design-logic is sound.
    Nevermind reading up on the particulars of your chosen DBMS and its differences to other systems.

    He’s using MS Access (see the file-extension «mdb» in his databasename?), and he’s not using access to bulletproof his queries in Access itself?
    That’s like:
    «Hey, i want to build a car from scratch all on my own, and have already started on doors and tires, but i have no idea how an engine works, or how the wiring is done»

    But i agree with you in one thing:
    He’s doing step 2 before having done step 1

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  11. Aug 21st, 2018, 07:32 PM


    #11

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by szlamany
    View Post

    Your DATE needs to be in quotes (if MS SQL) — maybe #’s if ACCESS.

    Using VAL() to turn a string into a number to then concatenate that «value» into a string is just silly. It is a «number» in the query because it is NOT IN QUOTES in that final query string.

    If this is MS SQL get the query to work in a QUERY WINDOW in Management Studio and then code logic that makes that EXACT SAME string,

    Bonjour j utilise une connection Access


  12. Aug 21st, 2018, 07:33 PM


    #12

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    bonjour j ai pas compris votre reponse


  13. Aug 21st, 2018, 07:39 PM


    #13

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Bonjour l erreur vient de la recherche sur la date car en suppriment la num�ro j ai la m�me erreur . avec ou sans #.
    Mais bravo a vous c est bien un logiciel pour voiture

    Last edited by siadli; Aug 21st, 2018 at 07:42 PM.


  14. Aug 21st, 2018, 08:36 PM


    #14

    Re: syntax error in number in query expression number and date in vb6

    English only here on this forum. Translate your post. Do it back to your language and back again to English might make your point clearer.


  15. Aug 22nd, 2018, 07:05 AM


    #15

    Re: syntax error in number in query expression number and date in vb6

    Utilises tu MS Access? Pardon, I mean, Sorry (Please use ENGLISH on this forum, even if you have to use a translator and copy-paste). It makes a difference which database you are using.

    Tell us which database, and then, show the exact NEW SQL statement that gives the ‘erreur’ (error).

    Sam


  16. Aug 22nd, 2018, 07:28 AM


    #16

    Re: syntax error in number in query expression number and date in vb6

    You appear to be using the old intrinsic DAO Data Control. Like the newer ADO Data Control these have many limitations. For example they are limited to a crude RecordSource property. They cannot handle parameter queries at all.

    When you use these super-simplified database connectors you can only specify a table name, a stored querydef with no parameters, or a SQL statement with no parameters.

    Code:

        Data1.RecordSource = "SELECT * FROM histo WHERE num�ro = " _
                           & LblNum�ro.Caption _
                           & " AND [date] = #" _
                           & Str$(CDate(ListeDate.Text)) _
                           & "#"

    [date] needs brackets because date (or DATE, Date, etc.) is the Date() function in Jet SQL. I am assuming that your «date» is a field name in the table «histo» here.

    CDate() converts a String value to a Date type value using the current session locale.

    Str$() converts a Variant value to a String value, and always uses the Invariant Locale. It is obsolete for most purposes but can be useful here because of the accidental side effect that it uses the Invariant Locale. If a Date type value is passed to it the resulting String value will be formatted properly for Jet SQL: m/d/yyyy format.


  17. Aug 22nd, 2018, 08:00 AM


    #17

    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by SamOscarBrown
    View Post

    Utilises tu MS Access? Pardon, I mean, Sorry (Please use ENGLISH on this forum, even if you have to use a translator and copy-paste). It makes a difference which database you are using.

    Tell us which database, and then, show the exact NEW SQL statement that gives the ‘erreur’ (error).

    Sam

    Sam,

    look at his first line in the first post. Take a look at his File-Extension…. «*.mdb»
    That’s Pre-2007 Access

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  18. Aug 22nd, 2018, 06:17 PM


    #18

    Re: syntax error in number in query expression number and date in vb6

    Ah..thanks Z….missed that one!


  19. Aug 23rd, 2018, 02:46 PM


    #19

    Re: syntax error in number in query expression number and date in vb6

    If its access it may also be complaining about the date format. not sure it will work with full stops.

    My usual advice is to convert to #mmm/dd/yyyy# or #dd/mmm/yyyy# as these are unambigous (ie clearer) than the #dd/mm/yyyy# or #mm/dd/yyyy# which I have had problems in the past with windows, excel and access settings in the locals messing the dates up.

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck…
    * Anything I post can be only my opinion. Advice etc is up to you to persue…


  20. Aug 24th, 2018, 12:51 AM


    #20

    Re: syntax error in number in query expression number and date in vb6

    Vince,

    the OP cross-posted the same question in the VB6-Forum, and i think dilettante was it, who showed a nifty way to avoid that conversion to locale-aware dateformat.
    I think it was something like «Str$(CDate(txtDate.Text))» or along those lines (too lazy to look up the thread now).

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  21. Aug 26th, 2018, 01:56 PM


    #21

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by Zvoni
    View Post

    Vince,

    the OP cross-posted the same question in the VB6-Forum, and i think dilettante was it, who showed a nifty way to avoid that conversion to locale-aware dateformat.
    I think it was something like «Str$(CDate(txtDate.Text))» or along those lines (too lazy to look up the thread now).

    hello it’s not a text box but a date list to retrieve in the database


  22. Aug 26th, 2018, 03:39 PM


    #22

    Re: syntax error in number in query expression number and date in vb6

    siadly,
    can you place your database here (with only the needed tables,and compacted, and zipped)
    and please explain clearly what you expect as a result

    do not put off till tomorrow what you can put off forever


  23. Aug 27th, 2018, 01:55 PM


    #23

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by IkkeEnGij
    View Post

    siadly,
    can you place your database here (with only the needed tables,and compacted, and zipped)
    and please explain clearly what you expect as a result

    as agreed, I made you a zip. the concern that i have, know i had programmed a management software in vb5 that works well ‘see the zip and putting it in vb6 after several modification of certain form works well jump that for form histo. the same function does not work anymore. I put the example that works in vb5 and the one in vb6 with the database. In fact I am looking for a visit of the customer thanks to the date with a drop-down list. I find all the dates of the customers but when I click on a date it puts the error 3075. I think it is the date that comes the error.
    Thank you for your intention and sorry for my poor English.


  24. Aug 27th, 2018, 02:21 PM


    #24

    Re: syntax error in number in query expression number and date in vb6

    does the following succeed ?

    Code:

    SELECT Num�ro, Date FROM Histo WHERE Num�ro=4 AND Date=#2017-06-29#

    do not put off till tomorrow what you can put off forever


  25. Aug 27th, 2018, 02:26 PM


    #25

    Re: syntax error in number in query expression number and date in vb6

    I suggested that same thing in post #2 — 22 posts ago.


  26. Aug 27th, 2018, 05:13 PM


    #26

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by IkkeEnGij
    View Post

    does the following succeed ?

    Code:

    SELECT Num�ro, Date FROM Histo WHERE Num�ro=4 AND Date=#2017-06-29#

    Hello, I tried to add #. but the error is always the same ….


  27. Aug 27th, 2018, 05:20 PM


    #27

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Hello, I tried to add #. but the error is always the same …. To fully understand my problem try to take the project in zip thank you friends of your supporters


  28. Aug 28th, 2018, 12:59 AM


    #28

    Re: syntax error in number in query expression number and date in vb6

    I’ve looked at his source-code.
    What’s wrong in this line (i see 2 errors)?

    Code:

    DataHisto.RecordSource = "select * from histo where date = # " & Format(ListeDateh, "dd.mm.yyyy") & " # "

    EDIT: Just saw it:
    That’s 7 days he wasn’t able to figure it out despite all hints and help he received

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  29. Aug 28th, 2018, 05:16 PM


    #29

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    Hello people from the forums

    After reading all your messages and testing by changing my locale by dd / MM / yyyy. for modified the date that becomes 28/08/2018 instead of 28.08.2018.

    My observations had a joy of thanks to all the participants.

    But I have a major concern that I can not understand is the first 12 days of each month «example: 01/03/2004 to 12/03/2004» the click on the list do not make any effect, then only on the other days of «13/05/2015 to 31/05/2015» it works. For what mystery reason.

    Did you have this problem?

    I have other questions to understand but try to find a solution for my 12th day that does not work …..

    And thank you for your precious help.


  30. Aug 28th, 2018, 09:29 PM


    #30

    Re: syntax error in number in query expression number and date in vb6

    there is no mysterious reason at all
    what is the date 05/06/2018 ?
    that depends on the part of the world you’r in
    it can mean the 5th day of June —say in belgium
    or the 6th day of may —say in the USA
    but: 2018/06/05 is the 5th day of june in any part of the world
    clearly you did not read/understand my post #24
    where i used the format YYYY-MM-DD for just that reason

    do not put off till tomorrow what you can put off forever


  31. Aug 29th, 2018, 01:10 AM


    #31

    Re: syntax error in number in query expression number and date in vb6

    Quote Originally Posted by siadli
    View Post

    After reading all your messages and testing by changing my locale by dd / MM / yyyy. for modified the date that becomes 28/08/2018 instead of 28.08.2018.

    Wrong!
    The Answer is in Post #16 in dilettante’s last line of the post.
    And he gave you a solution without Formatting the Date around three corners

    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ——————————————————————————————————————————————————————————————————————————————-

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ———————————————————————————
    People call me crazy because i’m jumping out of perfectly fine airplanes.
    ———————————————————————————
    Code is like a joke: If you have to explain it, it’s bad


  32. Aug 30th, 2018, 08:41 AM


    #32

    Re: syntax error in number in query expression number and date in vb6

    do not put off till tomorrow what you can put off forever


  33. Aug 30th, 2018, 02:05 PM


    #33

    siadli is offline

    Thread Starter


    New Member


    Re: syntax error in number in query expression number and date in vb6

    I come to you to thank, without you I think that I will not have succeeded. I had to
    My problem is that my french region uses the «.» for the date.
    Sorry for my mediocre English.

    my subject is this time resolved. Thank you very much

    Last edited by siadli; Aug 30th, 2018 at 02:16 PM.


  • Home
  • VBForums
  • Visual Basic
  • Database Development
  • syntax error in number in query expression number and date in vb6


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

See more:

Hi Guys,
I am doing an Electronic Library Management System that includes counting of time for each student who logged in every time he/she goes or used e-library. But I’m having trouble in frmReserve.

Here is the error that I got:
Syntax error in date in query expression ‘tblReserve.studID=tblStudents.StudNumber and tblReserve.inDate =#00/30/2012#’.

Below are m

<pre lang="vb">

y codes:
this code is executed when the command cmdLoad button is clicked

Private Sub cmdLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLoad.Click
       MsgBox(Today.ToString)
       paintStudList("SELECT tblReserve.pcNum, tblStudents.FullName, tblReserve.numOfTime FROM tblReserve,tblStudents where tblReserve.studID=tblStudents.StudNumber and tblReserve.inDate =#" & Today.ToString("mm/dd/yyyy") & "#", dgrid2, "PC NUMBER", "STUDENT NAME", "NUMBER OF TIME")
       dgrid2.Columns.Item(0).ReadOnly = True
       dgrid2.Columns.Item(1).ReadOnly = True
   End Sub

the following codes are executed if the SQL above is true

Sub paintStudList(ByVal newSQL As String, ByVal myGrid As System.Object, ByVal str1 As String, ByVal str2 As String, ByVal str3 As String)
        Dim adap1 As OleDbDataAdapter
        Dim dt1 As New DataTable
        Dim con As New OleDbConnection

        
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OleDb.4.0;Data Source=" & Application.StartupPath & "Library2.mdb; JET OleDb:Database Password=3Musketeers"
        

        adap1 = New OleDbDataAdapter(newSQL, con)
        con.Open()
        
        adap1.Fill(dt1)
        myGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing

        dt1.Columns.Item(0).ColumnName = str1
        dt1.Columns.Item(1).ColumnName = str2
        dt1.Columns.Item(2).ColumnName = str3
        myGrid.DataSource = dt1
        
        con.Close()
    End Sub

Hope someone could help me…
thanks in advance


Replace the «#» characters with quotes, and put the date into ISO format:

paintStudList("SELECT tblReserve.pcNum, tblStudents.FullName, tblReserve.numOfTime FROM tblReserve,tblStudents where tblReserve.studID=tblStudents.StudNumber and tblReserve.inDate ='" & Today.ToString("yyyy-MM-dd") & "'", dgrid2, "PC NUMBER", "STUDENT NAME", "NUMBER OF TIME")

If you used a parameterized query instead of this very shaky string concatentation, you wouldn’t have this problem at all and your code would be much more readable and maintainable.

VB.NET Parameterized Query[^]

Hi OriginalGriff,

I already resolved this by myself. The thing here is that, I did not noticed that the tblReserve.studID field on my database is in different data type (Text) whereas tblStudents.StudNumber is in Integer format. But still thanks for your quick response. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  • Remove From My Forums
  • Question

  • I have one select statement to execute on the access database on the click of a button. when i click on the button i am getting this error «Syntax error (missing operator) in query expression ‘Customer_Name = Summer Terry’.» The code that
    i have written is pasted below and also the error log. Can anyone please find and correct the error in my code.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.OleDb;
    
    namespace Cyber_Application
    {
        public partial class RegularCustomer : Form
        {
            int flag = 0;
            string currentFile;
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Clients\S V Cyber Cafe\Cyber Application\Cyber Application\param.accdb; Jet OLEDB:Database Password=12345";
    
            public RegularCustomer()
            {
                InitializeComponent();
            }
    
            private void btnOK_Click(object sender, EventArgs e)
            {
                string address = "";
                string date = "";
                string InTime = "";
                string OutTime = "";
                date = DateTime.Now.ToShortDateString();
                address = txtAddress.Text;
                InTime = txtInHour.Text + ":" + txtInMin.Text + " " + listBoxIn.SelectedItem.ToString();
                OutTime = txtOutHour.Text + ":" + txtOutMin.Text + " " + listBoxOut.SelectedItem.ToString();
                MessageBox.Show("Your address is:n" + address + "nToday's date is:n" + date + "nYour In Time is:n" + InTime + "nYour Out Time is:n" + OutTime);
            }
    
            private void btnCancel_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    
            private void addCustomers()
            {
                OleDbConnection cn = new OleDbConnection(connectionString);
                OleDbCommand cmd = new OleDbCommand("select Customer_Name from Customers", cn);
                cn.Open();
                OleDbDataReader dr = cmd.ExecuteReader();
    
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        cBoxCustomers.Items.Add(dr["Customer_Name"]);
                    }
                }
                cBoxCustomers.SelectedIndex = 0;
            }
    
            private void RegularCustomer_Load(object sender, EventArgs e)
            {
                addCustomers();
                btnOK.Enabled = false;
                btnBrowse.Enabled = false;
                btnSelectCustomer.Enabled = false;
                txtName.Enabled = false;
                txtAddress.Enabled = false;
                txtContactNo.Enabled = false;
                txtIdProof.Enabled = false;
                txtIssuedBy.Enabled = false;
            }
    
            private void cBoxCustomers_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (cBoxCustomers.SelectedIndex == 0)
                {
                    btnSelectCustomer.Enabled = false;
                }
                else
                {
                    btnSelectCustomer.Enabled = true;
                }
            }
    
            private void btnSelectCustomer_Click(object sender, EventArgs e)
            {
                using (OleDbConnection cn = new OleDbConnection(connectionString))
                {
                    cn.Open();
                    string scmd = "select [Customer_Name], [Address], [Contact_No], [Gender], [Issued_By] from Regular_Customers where Customer_Name = " + cBoxCustomers.SelectedItem.ToString();
                    OleDbCommand cmd = new OleDbCommand(scmd, cn);
                    OleDbDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        txtName.Text = sdr[0].ToString(); ;
                        txtAddress.Text = sdr[1].ToString();
                        txtContactNo.Text = sdr[2].ToString();
                        
                        if (sdr[3].ToString() == "M")
                        {
                            radioBtnMale.Select();
                        }
    
                        if (sdr[3].ToString() == "F")
                        {
                            radioBtnFemale.Select();
                        }
    
                        txtIssuedBy.Text = sdr[4].ToString();
                    }
                }
            }
        }
    }
    
    

    The error code is:

    System.Data.OleDb.OleDbException was unhandled
      Message=Syntax error (missing operator) in query expression 'Customer_Name = Summer Terry'.
      Source=Microsoft Office Access Database Engine
      ErrorCode=-2147217900
      StackTrace:
           at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
           at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
           at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
           at System.Data.OleDb.OleDbCommand.ExecuteReader()
           at Cyber_Application.RegularCustomer.btnSelectCustomer_Click(Object sender, EventArgs e) in E:ClientsS V Cyber CafeCyber ApplicationCyber ApplicationRegularCustomer.cs:line 90
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at Cyber_Application.Program.Main() in E:ClientsS V Cyber CafeCyber ApplicationCyber ApplicationProgram.cs:line 17
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    
    

    • Edited by

      Monday, September 26, 2011 3:30 AM

Answers

  • Instead of concatinating a string command, you would be better off using parameters.  I’m doing inserts into Access, but the code below should give you a general idea, of how to use parameters.  Then you don’t need to worry if you have all the
    single quotes in the correct places.

                        using (dal.DBManager db = new dal.DBManager(dal.DataProvider.OleDb,
                            string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}{1};",
                            this.db_Directory, this.db_FileName)))
                        {
                            db.Open();
    
                            foreach (DataRow row in dt.Rows)
                            {
                                this.CurCount++;
                                this.TotalCount = (short)(((float)this.CurCount / (float)dt.Rows.Count) * 100);
                                this.StatusMessage = string.Format(Msg, this.CurCount, dt.Rows.Count.ToString(), this.TotalCount.ToString());
    
                                db.Command.CommandText = "INSERT INTO [ProgramLanguage Join](ProgramID, LanguageID, AudioFormatID) VALUES(?, ?, ?)";
    
                                db.CreateParameters(3);
    
                                db.AddParameters(0, "ProgramID", Convert.ToInt32(row["ProgramID"]));
                                db.AddParameters(1, "LanguageID", Convert.ToInt16(row["LanguageID"]));
                                db.AddParameters(2, "AudioFormatID", Convert.ToInt16(row["AudioFormatID"]));
    
                                db.ExecuteNonQuery(CommandType.Text, db.Command.CommandText);
    
                                worker.ReportProgress(this.TotalCount, StatusMessage);
                            }
    
                            db.Close();
                        }
    
    • Marked as answer by
      Martin_Xie
      Thursday, September 29, 2011 5:29 AM

  • enclose the value that you would like to pass with ( ‘ )… as in your code:

     « + cBoxCustomers.SelectedItem.ToString();

    should be: ‘« + cBoxCustomers.SelectedItem.ToString() +
    ««;

    • Edited by
      RoninB
      Monday, September 26, 2011 3:38 AM
    • Marked as answer by
      tapan.desai
      Monday, September 26, 2011 6:17 AM

  • hi Tapan,

    please try this:

    string scmd = "select [Customer_Name], [Address], [Contact_No], [Gender], [Issued_By] from Regular_Customers where Customer_Name = '" + cBoxCustomers.SelectedItem.ToString()+"'";
    
    

    Regards, http://shwetamannjain.blogspot.com

    • Proposed as answer by
      Shweta Jain (Lodha)
      Monday, September 26, 2011 3:41 AM
    • Marked as answer by
      tapan.desai
      Monday, September 26, 2011 6:17 AM

Понравилась статья? Поделить с друзьями:
  • Syntax error in from clause
  • Syntax error in data declaration at 1
  • Syntax error identifier expected but var found
  • Syntax error identifier expected but function found
  • Syntax error gothic 3