Syntax error in from clause

User-269982159 posted
  • Remove From My Forums
  • Question

  • User-269982159 posted

    hey i have occur error from this SELECT  statement … pls help (:

    error : syntax error in FROM clause

     public void readUser()
            {
                OleDbConnection Con = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0; Data Source=C:UsershpDocumentsVisual Studio 2008ProjectsPATS_084623QPATS_084623QDatabasePATS.mdb");
                try
                {
                    Con.Open();
    
    
                    string select = "SELECT CapturedImage FROM RegisteredUserParticulars" + "WHERE WindowsUserName = '" + win_user_name + "'";
                    OleDbCommand command = new OleDbCommand(select, Con);
                    OleDbDataReader reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        Byte[] image_to_read = (Byte[])reader.GetValue(0);
                        FileStream fs = new FileStream(sPath + win_user_name + "_face.jpg", FileMode.Create);
                        BinaryWriter bw = new BinaryWriter(fs);
                        bw.Write(image_to_read);
                        bw.Close();
                        fs.Close();
                    }
                    Con.Close();
                    eventLog1.WriteEntry("FACE READ OK!");
                }
                catch (OleDbException e)
                {
                    eventLog1.WriteEntry(e.Message);
                }
            }

    thnk u (:

Answers

  • User-1179452826 posted

    1. The error is coz you don’t have a space between RegisteredUserParticulars and WHERE. Add a space. 

    2. What you’re doing with concatenating parameters in the sql query is criminal. Do a quick search on the internet for sql injection and try to use parameterized queries instead.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User-1199946673 posted

    hey .. i have change to the above mention … however .. now my error turn out to be : NO VALUE GIVEN FOR ONE OR MORE REQUIRED PARAMETERS …

     

    Hey come on. In you other post your using Parameterized queries, and here you don’t. Please read this (again, because I already pointed to this article before):

    http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access

    Also, in you other post you had the same error. Is it your intention everytime you’ve an error, to start opening a new thread, or is it your intention to learn from what your told? In the other thread, I also mentioned another reason why you could get this
    error:

    If your error is still ‘No value given for one or more required parameters.’, please check if you didn’t misspelled one (or more) fieldnames in the commandtext?

     

    It could also be a misspelled tablename!

    Another thing is that you hardcode the connectionstring. When you go into production, this is not a good idea, because the path most likely will change. You should store the connectionstring in your web.config.

    http://www.mikesdotnetting.com/Article/78/AccessDataSource-SqlDataSource-and-connecting-to-Access-databases-in-ASP.NET

    Also note the remarks in this article where to save the database….

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Содержание

  1. [Microsoft][ODBC Text Driver] Syntax error in FROM clause.
  2. Troubleshooting
  3. Problem
  4. Resolving The Problem
  5. SQL Errors: Five Common SQL Mistakes
  6. Watch Your Language (and Syntax)
  7. 1. Misspelling Commands
  8. Solution:
  9. 2. Forgetting Brackets and Quotes
  10. Solution:
  11. 3. Invalid statement order
  12. Solution:
  13. 4. Omitting Table Aliases
  14. Solution:
  15. 5. Using Case-Sensitive Names
  16. Solution:
  17. Everybody Makes SQL Mistakes

[Microsoft][ODBC Text Driver] Syntax error in FROM clause.

Troubleshooting

Problem

Problem Number Error Error number -3989587 DMS-E-GENERAL, A General Exception has occurred during operation ‘prepare request’. DMS-E-DBPARSER, The underlying database detected an error during processing of the SQL request. [Microsoft][ODBC Text Driver] Syntax error in FROM clause. when querying an ODBC datasource using the Microsoft ODBC Text Driver. Solution Description This error is due to an issue with the ODBC driver. Microsoft have documented this issue in their Knowledge Base articles #Q124322, Q125959 and Q124319. Please contact Microsoft for further information on this issue. As a workaround it may be possible to Qualify the Tables Less in the Catalog Tables dialog window. It may also be necessary to change the delimiter type in the ODBC drivers options, and to use Escape Metacharacters when retrieving the data. This option is also set in the Options for the ODBC driver. The problem is due to the driver not supporting quoted schema’s or tables thus to eliminate the problem the attach must be made using the connection parameter DELIMIT=COL. Microsoft offers the following as a workaround. Please contact Microsoft for further information on this technique. These workarounds are not set within Impromptu but are for the Driver. Method 1: Name the range something other than «Database» or «Table.» Method 2: If you are accessing data from a Microsoft Excel 5.0 workbook that contains a global range named «Database» or «Table,» define it as a local range name, such as «Sheet1!Database.» Note that making the name a local one will cause the table name to be displayed with the sheet name and then the range name: Sheet1!Database. Method 3: Add brackets ([) around the words «Database» or «Table.» For example, to select all records from a table called Database, follow these steps: a. In Microsoft Query, click the SQL button on the toolbar. This displays the SQL dialog box. b. In the dialog box, type the following SQL statement: SELECT * FROM [Database] c. Choose OK. A message will appear stating that the query cannot be represented graphically. d. Choose Yes to continue. This displays only the Data pane in the query window.

Resolving The Problem

This error is due to an issue with the ODBC driver. Microsoft have documented this issue in their Knowledge Base articles #Q124322, Q125959 and Q124319. Please contact Microsoft for further information on this issue.

As a workaround it may be possible to Qualify the Tables Less in the Catalog Tables dialog window. It may also be necessary to change the delimiter type in the ODBC drivers options, and to use Escape Metacharacters when retrieving the data. This option is also set in the Options for the ODBC driver.

The problem is due to the driver not supporting quoted schema’s or
tables thus to eliminate the problem the attach must be made using the
connection parameter DELIMIT=COL.

Microsoft offers the following as a workaround. Please contact Microsoft for further information on this technique. These workarounds are not set within Impromptu but are for the Driver.

Method 1: Name the range something other than «Database» or «Table.»

Method 2: If you are accessing data from a Microsoft Excel 5.0 workbook
that contains a global range named «Database» or «Table,» define
it as a local range name, such as «Sheet1!Database.» Note that
making the name a local one will cause the table name to be
displayed with the sheet name and then the range name:
Sheet1!Database.

Method 3: Add brackets ([) around the words «Database» or «Table.» For
example, to select all records from a table called Database,
follow these Steps:a. In Microsoft Query, click the SQL button on the toolbar.

This displays the SQL dialog box.

b. In the dialog box, type the following SQL statement:

SELECT * FROM [Database]

A message will appear stating that the query cannot be
represented graphically.

d. Choose Yes to continue.

This displays only the Data pane in the query window.

Источник

SQL Errors: Five Common SQL Mistakes

As you learn SQL, watch out for these common coding mistakes

You’ve written some SQL code and you’re ready to query your database. You input the code and …. no data is returned. Instead, you get an error message.

Don’t despair! Coding errors are common in any programming language, and SQL is no exception. In this article, we’ll discuss five common mistakes people make when writing SQL.

The best way to prevent mistakes in SQL is practice. LearnSQL.com offers over 30 interactive SQL courses. Try out our SQL Practice track with 5 courses and over 600 hands-on exercises.

Watch Your Language (and Syntax)

The most common SQL error is a syntax error. What does syntax mean? Basically, it means a set arrangement of words and commands. If you use improper syntax, the database does not know what you’re trying to tell it.

To understand how syntax works, we can think of a spoken language. Imagine saying to a person “Nice dof” when you mean “Nice dog”. The person does not know what “dof” means. So when you tell your database to find a TABEL instead of a TABLE, the database does not know what it needs to do.

People tend to make the same kinds of syntax mistakes, so their errors are usually easy to spot and very much the same. After you read this article, you should be able to remember and avoid (or fix) these common mistakes. Knowing what errors to look for is very important for novice SQL coders, especially early on. New coders tend to make more mistakes and spend more time looking for them.

The types of SQL errors we will look at are:

  1. Misspelling Commands
  2. Forgetting Brackets and Quotes
  3. Specifying an Invalid Statement Order
  4. Omitting Table Aliases
  5. Using Case-Sensitive Names

Ready? Let’s start.

SQL Errors:

1. Misspelling Commands

This is the most common type of SQL mistake among rookie and experienced developers alike. Let’s see what it looks like. Examine the simple SELECT statement below and see if you can spot a problem:

If you run this query, you’ll get an error which states:

Each database version will tell you the exact word or phrase it doesn’t understand, although the error message may be slightly different.

What is wrong here? You misspelled FROM as FORM. Misspellings are commonly found in keywords (like SELECT, FROM, and WHERE), or in table and column names.

Most common SQL spelling errors are due to:

  • “Chubby fingers” where you hit a letter near the right one: SELEVT or FTOM or WJIRE
  • “Reckless typing” where you type the right letters in the wrong order: SELETC or FORM or WHEER

Solution:

Use an SQL editor that has syntax highlighting: the SELECT and WHERE keywords will be highlighted, but the misspelled FORM will not get highlighted.

If you’re learning with interactive SQL courses in LearnSQL.com , the code editor puts every SELECT statement keyword in light purple. If the keyword is black, as it is with any other argument, you know there’s a problem. (In our example, FORM is black).

So if we correct our statement we get:

The keyword is now the right color and the statement executes without an error.

2. Forgetting Brackets and Quotes

Brackets group operations together and guide the execution order. In SQL (and in all of the programming languages I use), the following order of operations …

… is not the same as:

Can you figure out why?

A very common SQL mistake is to forget the closing bracket. So if we look at this erroneous statement :

We get an error code with the position of the error (the 102nd character from the beginning):

Remember: brackets always come in pairs.

The same is true with single quotes ( ‘ ‘ ) or double quotes ( ” ” ). There is no situation in SQL where we would find a quote (either a single quote or a double quote) without its mate. Column text values can contain one quote ( e.g. exp.last_name = «O’Reilly» ) and in these situations we must mix two types of quotes or use escape characters. ( In SQL, using escape characters simply means placing another quote near the character you want to deactivate – e.g. exp.last_name = ‘O’’Reilly. )

Solution:

Practice, practice, practice. Writing more SQL code will give you the experience you need to avoid these mistakes. And remember people usually forget the closing bracket or quotation mark. They rarely leave out the opening one. If you’re running into problems, take a close look at all your closing punctuation!

3. Invalid statement order

When writing SELECT statements, keep in mind that there is a predefined keyword order needed for the statement to execute properly. There is no leeway here.

Let’s look at an example of a correctly-ordered statement:

There’s no shortcut here; you simply have to remember the correct keyword order for the SELECT statement:

  • SELECT identifies column names and functions
  • FROM specifies table name or names (and JOIN conditions if you’re using multiple tables)
  • WHERE defines filtering statements
  • GROUP BY shows how to group columns
  • HAVING filters the grouped values
  • ORDER BY sets the order in which the results will be displayed

You cannot write a WHERE keyword before a FROM , and you can’t put a HAVING before a GROUP BY . The statement would be invalid.

Let’s look at what happens when you mix up the statement order. In this instance, we’ll use the common SQL error of placing ORDER BY before GROUP BY :

The error message we see is pretty intimidating!

Solution:

Don’t be discouraged! You can see that all of the keywords are highlighted correctly and all the quotations and brackets are closed. So now you should check the statement order. When you’re just beginning your SQL studies, I suggest using a SELECT order checklist. If you run into a problem, refer to your list for the correct order.

4. Omitting Table Aliases

When joining tables, creating table aliases is a popular practice. These aliases distinguish among columns with the same name across tables; thus the database will know which column values to return. This is not mandatory when we’re joining different tables, since we can use the full table names. But it is mandatory if we join a table to itself.

Suppose we’re writing an SQL statement to find an exhibition’s current location and the location from the previous year:

The database would return an error:

Note: Whenever you encounter “ambiguous column name” in your error message, you surely need table aliases.

The correct statement (with aliases) would be:

Solution:

Practice using table aliases for single-table SELECT statements. Use aliases often – they make your SQL more readable.

5. Using Case-Sensitive Names

This error only occurs when you need to write non-standard names for tables or database objects.

Let’s say that you need to have a table named LargeClient and for some reason you add another table called LARGECLIENT. As you already know, object names in databases are usually case-insensitive. So when you write a query for the LargeClient table, the database will actually query LARGECLIENT.

To avoid this, you must put double quotes around the table name. For example:

When creating a table, you will need to use double quotes if:

  • The table will have a case-sensitive name.
  • The table name will contain special characters. This includes using a blank space, like “Large Client”.

Solution:

Avoid using these names if you can. If not, remember your double quotes!

Everybody Makes SQL Mistakes

Those are the five most common errors in SQL code. You’ll probably make them many times as you learn this language. Remember, everybody makes mistakes writing code. In fact, making mistakes is a normal and predictable part of software development.

So don’t be discouraged. When you make mistakes in the future, try to analyze your code in a structured way. With a structured analysis, you can find and correct your errors quicker.

If you would like to learn about some other syntactic mistakes that I’ve not included here, please let me know. In an upcoming article, we’ll look at non-syntactic errors. These return or modify data and are therefore much more dangerous. Subscribe to our blog so you won’t miss it!

Источник

  • Remove From My Forums
  • Question

  • i am getting this error when I try and select data from my access database. I’ve tried changing the position of the colons but it hasnt produced the required result. can anyone help on what could be wrong with my FROM clause. I am using VB^ and MS ACCESS

                                                Set rst = New ADODB.Recordset
                                                rst.Open "SELECT * FROM SundryProduct WHERE ProdCont=' " & txt_con_code.Text & " ' ", Cnn, adOpenForwardOnly, , adCmdTable
                                                If rst.EOF Then
                                                MsgBox ("SEARCH FAILED")
                                                Else
                                                
                                                MsgBox ("QUANTITY ORDERED  " & rstContractsProduct!QuantityOrdered & "   My Load Number is   " & rst!LoadNumber)
                                                End If
    


    If you think it you can achieve it

Answers

  •  rst.Open "SELECT * FROM SundryProduct WHERE ProdCont=' " & txt_con_code.Text & " ' ", Cnn, adOpenForwardOnly, , adCmdTable                                            

    Hello,

    You open the command as a adCmdTable, so only the table name is expected, not a complete SQL query. Change it to
    adCmdText to get it working; see
    CommandTypeEnum


    Olaf Helper

    Blog
    Xing

    • Edited by

      Thursday, May 2, 2013 10:29 AM

    • Proposed as answer by
      Marko Frntic
      Thursday, May 2, 2013 10:45 AM
    • Marked as answer by
      tendaimare
      Thursday, May 2, 2013 10:58 AM

  • #1

Hi

Using a pivot table in Excel to connect to a Table of external data in Access

ie I select get data from External Database/Access

microsoft query starts and everything works fine until I get to the final
section and when I push finish to display the data in Excel I get an error message

«Syntax error in FROM clause»

So I google this and get to the Microsoft website where I get the following explanation:

SYMPTOMS
When you use Microsoft Query to return external data to a worksheet in Microsoft Excel or when you view returned data in Microsoft Query, you may receive the following error message:
Syntax error in FROM clause.
Back to the top

CAUSE
This problem occurs if you attempt to retrieve data from a Microsoft Access or Microsoft Excel database, and the path to the database contains a period (.), for example:
C:My.TestNorthwind.mdb
Back to the top

WORKAROUND
To work around this problem, change the path to the database so that it does not contain any periods, for example:
C:MyTestNorthwind.mdb C:My TestNorthwind.mdb

As I work on a network my filepath always has a «.» between my first and surname
ie R:/Joe.Bloggs/DB1

So I find a location on the network where there is not a «. «contained in the path and put it there but get same error

So I put it on a memory stick and still the same error when I try to connect via the pivot table

Does anyone know what I am doing wrong?

Kind Regards

Thomas

How to find 2nd largest value in a column?

MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest

  • #2

Hi Thomas, Ive recreated your problem and its annoying alright. I can only think of 2 options to resolve this.

1) If you have the ability to map a network drive (personally everything is locked down at my work so I cant but hopefully you can) then you can map your directory R:Joe.BloggsDB1 to another letter, say Z. So now you can just browse to letter Z: and then select the file.

2) If you are unable to map the drive then I don’t think you can use menu driven Excel connection method to the database. The following is some code I wrote that connects to a database. As you can see in the Conn.Open below this doesn’t care whether the directory has a dot or not. You are going to have to know SQL so if you dont its not hard — see the web site http://www.w3schools.com/sql/sql_select.asp.

Code:

Sub ConnectToDatabase()
Dim Conn As Object, StrSQL As String, Rs As Object

'Connect to your database
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "Microsoft.Jet.OLEDB.4.0"
Conn.Open "C:Joe.BlogsDb1Db2.mdb" 'This is your path to the file

'Create SQL for the query yo need
StrSQL = "SELECT * FROM EMPLOYEE" 'This is the SQL of what data you want to return

'Open a recordset of the data you want
Set Rs = CreateObject("ADODB.Recordset")
Rs.Open StrSQL, Conn

'Put data into Excel
Worksheets("Sheet2").Range("A1").CopyFromRecordset Rs 'This is where the data is populated

'Close recordset and termintae connection to the database
Rs.Close
Conn.Close


End Sub

Good luck.

regards,
Graham

Last edited: Oct 31, 2008

  • #3

Hi Graham

Firstly apologies for not replying earlier, was away this weekend and have just logged into my computer.

Thank you very much for your help in this regard this certainly explains why it is not working and have saved me a few more hours banging my head against the keyboard while I try to work out what is going on.

Like yourself my company locks down the mapping of its drives so I think the ADO soloution is extremely viable (thank you).

Just one problem I cannot export the data from access to excel as it exceeds 65536 rows (using 2003) hence my reason for putting the pivot table data in an access table.

Show below is the code I would normally use to create a pivot table:

Set wsd = Worksheets(«Over Days»)
Worksheets(«Over Days»).Activate
finalrow = wsd.Cells(65536, 1).End(xlUp).Row
Set prange = wsd.Cells(5, 1).Resize(finalrow, 7)

Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:=prange.Address)
Set wsd = Worksheets(«OLDEST»)
Set pt = PTCache.CreatePivotTable(TableDestination:=wsd.Range(«B8″), TableName:=»PivotTable1»)

Do you know if I could modify the vba code below:

Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:=prange.Address)

ie change «Source Type» to an access database and «SourceData» to an access table
maybe in combination with ADO?

If so have you any idea how the code would look?

Any help would be greatly appreciated

Best Wishes

Thomas

  • #4

Hi Thomas, if you look in the VBE Help under the topic CreatePivotTable Method there’s an example in there on using an ADODB connection to an Access database. You need to create a connection to the Db and then when you add the PivotCache you use SourceType:=xlExternal and then set the Recordset property for the cache to the recordset you created during the connection process.

Heres the example code from the Help…
This example creates a new PivotTable cache using an ADO connection to Microsoft Jet, and then it creates a new PivotTable report based on the cache, at cell A3 on the active worksheet.

Code:

Sub VBEHelp_Example()
Dim cnnConn As ADODB.Connection
Dim rstRecordset As ADODB.Recordset
Dim cmdCommand As ADODB.Command

' Open the connection.
Set cnnConn = New ADODB.Connection
With cnnConn
    .ConnectionString = _
        "Provider=Microsoft.Jet.OLEDB.4.0"
    .Open "C:perfdaterecord.mdb"
End With

' Set the command text.
Set cmdCommand = New ADODB.Command
Set cmdCommand.ActiveConnection = cnnConn
With cmdCommand
    .CommandText = "Select Speed, Pressure, Time From DynoRun"
    .CommandType = adCmdText
    .Execute
End With

' Open the recordset.
Set rstRecordset = New ADODB.Recordset
Set rstRecordset.ActiveConnection = cnnConn
rstRecordset.Open cmdCommand

' Create a PivotTable cache and report.
Set objPivotCache = ActiveWorkbook.PivotCaches.Add( _
    SourceType:=xlExternal)
Set objPivotCache.Recordset = rstRecordset
With objPivotCache
    .CreatePivotTable TableDestination:=Range("A3"), _
        TableName:="Performance"
End With

With ActiveSheet.PivotTables("Performance")
    .SmallGrid = False
    With .PivotFields("Pressure")
        .Orientation = xlRowField
        .Position = 1
    End With
    With .PivotFields("Speed")
        .Orientation = xlColumnField
        .Position = 1
    End With
    With .PivotFields("Time")
        .Orientation = xlDataField
        .Position = 1
    End With
End With

' Close the connections and clean up.
cnnConn.Close
Set cmdCommand = Nothing
Set rstRecordset = Nothing
Set cnnConn = Nothing

End Sub

  • #5

Hi Graham

Thank you very much for the code, I cant tell you how much you have helped me sort this problem out.

Best Wishes

Thomas

  • #6

My pleasure Thomas, glad you have it sorted.

Понравилась статья? Поделить с друзьями:
  • 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
  • Syntax error expected name found