Syntax error at or near into

Hi there all I am using the psycopg2 module for postgresql and I keep receiving an error in my SQL statement saying there is a syntax error at or near 'INSERT INTO. I've stared at it forever and I just can't seem to find it, maybe someone can help m...

Jul-18-2017, 02:54 AM
(This post was last modified: Jul-18-2017, 02:55 AM by olgethorpe.)

Hi there all

I am using the psycopg2 module for postgresql and I keep receiving an error in my SQL statement saying there is a syntax error at or near «INSERT INTO. I’ve stared at it forever and I just can’t seem to find it, maybe someone can help me? Thanks!

The connection is working fine between the database, and dates is a list of dates also autocommit is set to True

def addToDatabase(self, dates):
.
.
.
   sql = """INSERT INTO "%s" ("Date") VALUES(%s);"""

       for date in range(0, len(dates)):
           data = (ticker, dates[date])
           cursor.execute(sql, data)
.
.
.

Posts: 11,568

Threads: 446

Joined: Sep 2016

Reputation:
444

Please:

  • Show the code in context
  • Show actual (verbatim) error traceback

Thank you

Posts: 2

Threads: 1

Joined: Jul 2017

Reputation:
0

The error traceback is as follows:
Traceback (most recent call last):
  File «stockMain.py», line 21, in <module>
    main()
  File «stockMain.py», line 8, in main
    databases.addToDatabases(databases.dataFeed.genDates[‘daily’])
  File «/home/dondusko/Documents/AtomProjects/StockProject/stockDatabase.py», line 110, in addToDatabases
    cursor.execute(sql, data)
psycopg2.ProgrammingError: syntax error at or near «INSERT INTO»
LINE 1: INSERT INTO «‘AAPL'» («Date») VALUES(‘2008-01-01’);

This is the function in question, not exactly sure what you mean code in context so this might be helpful?:

def addToDatabases(self, dates):
       ticker = self.getTickerName()

       for databaseName in range(0, len(self.databaseNames)):
           tempConnection = psycopg2.connect(dbname="'"+self.databaseNames[databaseName]+"'", user=self.databaseCredentials['username'], host=self.databaseCredentials['host'], password=self.databaseCredentials['password'])
           cursor = tempConnection.cursor()
           tempConnection.autocommit = True

           sql = """CREATE TABLE IF NOT EXISTS "%s" (""" + self.getTableSQL() + ");"
           data = (ticker, )
           cursor.execute(sql, data)

           sql = """INSERT INTO "%s" ("Date") VALUES(%s);"""

           for date in range(0, len(dates)):
               data = (ticker, dates[date])
               cursor.execute(sql, data)

           cursor.close()
           tempConnection.close()

Posts: 11,568

Threads: 446

Joined: Sep 2016

Reputation:
444

add a print statement after line 9

print(sql: {}'.format(sql))

Posts: 3,458

Threads: 101

Joined: Sep 2016

Reputation:
143

Jul-21-2017, 07:39 PM
(This post was last modified: Jul-21-2017, 07:40 PM by nilamo.)

(Jul-18-2017, 03:58 AM)olgethorpe Wrote: INSERT INTO «‘AAPL'»

I don’t know postgres, but for most databases, it’s an sql error to quote a table name.  If you can’t just use the table name (ie: insert into AAPL), you could use brackets (ie: insert into [AAPL]), or sometimes backticks.

Syntax errors are quite common while coding.

But, things go for a toss when it results in website errors.

PostgreSQL error 42601 also occurs due to syntax errors in the database queries.

At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.

Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.

What causes error 42601 in PostgreSQL?

PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.

Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.

But what causes error 42601?

PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.

Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.

In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.

How we fix the error?

Now let’s see how our PostgreSQL engineers resolve this error efficiently.

Recently, one of our customers contacted us with this error. He tried to execute the following code,

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;

But, this ended up in PostgreSQL error 42601. And he got the following error message,

ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)

Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,

RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;

This resolved the error 42601, and the code worked fine.

[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]

Conclusion

In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I am creating a java web application using MyBatis and postgres.
If i execute insert query as shown below, an error will occur.

■ MyBatis xml file

&lt;insert id = "insertRace"&gt;
        insert into t_race (race_id, obstacle_flg, race_name, grade, race_number, field_type, distance, rotate_type, weather, field_condition, host_id, post_time, host_date, host_times, host_days, horse_type, age_condition, product_condition, appointed_condition, sex_condition, weight_condition, insert_date, insert_user, update_date, update_user)
        values ​​('${raceId}', ${obstacleFlg}, '${raceName}', '${grade}', ${raceNumber}, '${fieldType}', ${distance}, '${rotateType} ',' ${weather} ',' ${fieldCondition} ',' ${hostId} ', ${postTime}, ${hostDate}, ${hostTimes}, ${hostDays}, ${horseType},' ${ageCondition} ', ${productCondition}, ${appointedCondition}, ${sexCondition}, ${weightCondition}, CURRENT_TIMESTAMP,' SYSTEM ', CURRENT_TIMESTAMP,' SYSTEM ')
    &lt;/insert&gt;

■ Errors output by postgres

ERROR: syntax error at or near ":" at character 433
STATEMENT: insert into t_race (race_id, obstacle_flg, race_name, grade, race_number, field_type, distance, rotate_type, weather, field_condition, host_id, post_time, host_date, host_times, host_days, horse_type, age_condition, product_condition, appointed_condition, sex_condition, weight_condition, insert_date, insert_user, update_date, update_user)
            values ​​('201606020302', 0, '3 years old not won', 'not won', 2, 'dirt', 1200, 'right', 'cloudy', 'good', '06', 10:40:00, 2016-03-05, 2, 3, 1, '3 years old', 1, 2, 999, 4, CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM')

■ java console exception

### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 433
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into t_race (race_id, obstacle_flg, race_name, grade, race_number, field_type, distance, rotate_type, weather, field_condition, host_id, post_time, host_date, host_times, host_days, horse_type, age_condition, product_condition, appointed_condition, sex_condition, weight_condition , insert_date, insert_user, update_date, update_user) values ​​('201606020302', 0, '3 years old not won', 'not won', 2, 'dirt', 1200, 'right', 'cloudy', 'good', ' 06 ', 10:40:00, 2016-03-05, 2, 3, 1,' 3 years old ', 1, 2, 999, 4, CURRENT_TIMESTAMP,' SYSTEM ', CURRENT_TIMESTAMP,' SYSTEM ')
### Cause: org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 433
bad SQL grammar [];nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 433] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 433
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse (QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults (QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute (QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute (AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags (AbstractJdbc2Statement.java:388)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute (AbstractJdbc2Statement.java:381)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.update (PreparedStatementHandler.java:45)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.update (RoutingStatementHandler.java:73)at org.apache.ibatis.executor.SimpleExecutor.doUpdate (SimpleExecutor.java:49)
    at org.apache.ibatis.executor.BaseExecutor.update (BaseExecutor.java:115)
    at org.apache.ibatis.executor.CachingExecutor.update (CachingExecutor.java:75)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update (DefaultSqlSession.java:170)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.insert (DefaultSqlSession.java:157)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:483)
    at org.mybatis.spring.SqlSessionTemplate $SqlSessionInterceptor.invoke (SqlSessionTemplate.java:358)
    at com.sun.proxy. $Proxy12.insert (Unknown Source)
    at org.mybatis.spring.SqlSessionTemplate.insert (SqlSessionTemplate.java:240)
    at org.apache.ibatis.binding.MapperMethod.execute (MapperMethod.java:52)
    at org.apache.ibatis.binding.MapperProxy.invoke (MapperProxy.java:53)
    at com.sun.proxy. $Proxy24.insertRace (Unknown Source)
    at jp.keiba.analitics.service.ScrapingDataService.insertRace (ScrapingDataService.java:169)
    at jp.keiba.analitics.service.ScrapingDataService.insertAll (ScrapingDataService.java:45)
    at jp.keiba.analitics.controller.scraping.UrlRaceScrpController.raceComplete (UrlRaceScrpController.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:483)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest (InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod (RequestMappingHandlerAdapter.java:817)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:731)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle (AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService (DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest (FrameworkServlet.java:968)at org.springframework.web.servlet.FrameworkServlet.doGet (FrameworkServlet.java:859)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal (CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke (AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke (AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process (AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol $AbstractConnectionHandler.process (AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint $SocketProcessor.run (JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor $Worker.run (ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread $WrappingRunnable.run (TaskThread.java:61)
    at java.lang.Thread.run (Thread.java:745)

I don’t use»:»in the query and I’m not sure why the error message is ERROR: syntax error at or near»:».
We are very happy if you can help us.

@YohDeadfall — I understand that part about it, but this is not script that I am creating or even code that I am creating. This is all created under the hood by Npsql/EntityFramework. My quick guess is that I am extending my DbContext from IdentityDbContext<IdentityUser> which wants to create all of the tables for roles, users, claims, etc. If I change this to just extend from DbContext, then everything works as advertised.

Below is the script that EF is trying to use created from dotnet ef migrations script — please be aware that I have removed my custom part of the script for brevity.

You can see there are two specific calls that are being made where [NormalizedName] and [NormalizedUserName] are being used.

CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
    "MigrationId" varchar(150) NOT NULL,
    "ProductVersion" varchar(32) NOT NULL,
    CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

CREATE TABLE "AspNetRoles" (
    "Id" text NOT NULL,
    "ConcurrencyStamp" text NULL,
    "Name" varchar(256) NULL,
    "NormalizedName" varchar(256) NULL,
    CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);

CREATE TABLE "AspNetUsers" (
    "Id" text NOT NULL,
    "AccessFailedCount" int4 NOT NULL,
    "ConcurrencyStamp" text NULL,
    "Email" varchar(256) NULL,
    "EmailConfirmed" bool NOT NULL,
    "LockoutEnabled" bool NOT NULL,
    "LockoutEnd" timestamptz NULL,
    "NormalizedEmail" varchar(256) NULL,
    "NormalizedUserName" varchar(256) NULL,
    "PasswordHash" text NULL,
    "PhoneNumber" text NULL,
    "PhoneNumberConfirmed" bool NOT NULL,
    "SecurityStamp" text NULL,
    "TwoFactorEnabled" bool NOT NULL,
    "UserName" varchar(256) NULL,
    CONSTRAINT "PK_AspNetUsers" PRIMARY KEY ("Id")
);

CREATE TABLE "AspNetRoleClaims" (
    "Id" int4 NOT NULL,
    "ClaimType" text NULL,
    "ClaimValue" text NULL,
    "RoleId" text NOT NULL,
    CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserClaims" (
    "Id" int4 NOT NULL,
    "ClaimType" text NULL,
    "ClaimValue" text NULL,
    "UserId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserLogins" (
    "LoginProvider" text NOT NULL,
    "ProviderKey" text NOT NULL,
    "ProviderDisplayName" text NULL,
    "UserId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey"),
    CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserRoles" (
    "UserId" text NOT NULL,
    "RoleId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId"),
    CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE,
    CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserTokens" (
    "UserId" text NOT NULL,
    "LoginProvider" text NOT NULL,
    "Name" text NOT NULL,
    "Value" text NULL,
    CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name"),
    CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ("RoleId");

CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" ("NormalizedName") WHERE [NormalizedName] IS NOT NULL;

CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ("UserId");

CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ("UserId");

CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ("RoleId");

CREATE INDEX "EmailIndex" ON "AspNetUsers" ("NormalizedEmail");

CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" ("NormalizedUserName") WHERE [NormalizedUserName] IS NOT NULL;

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20180514204732_initial', '2.0.3-rtm-10026');

Понравилась статья? Поделить с друзьями:
  • Syntax error at or near for postgresql
  • Svchost exe что это ошибка
  • Syntax error at or near at character
  • Syntax error at or near array
  • Svchost exe системное предупреждение unknown hard error