sqlite3.OperationalError: near "values" syntax error [duplicate] - python

I'm trying out statements for creating a database, and after 10 entities without any issues I ran into this error
Error: Near line 83: near "Transaction": syntax error
The first line is line 83 with it's context of creating a table
CREATE TABLE Transaction (
TransactionID INTEGER,
AccountID INTEGER REFERENCES User (AccountID),
ItemID INTEGER REFERENCES Item (ItemID),
Method STRING,
Price INTEGER,
TransactionDate DATE,
PRIMARY KEY (TransactionID)
);
Now I can't seem to find the issue, and suggestion's of something with ASCII using the wrong space couldn't be solved by writing the same thing again manually.
I haven't even gotten around to checking the integrity of my foreign keys, and it's not working. Hopefully somebody could provide some insight on what I'm missing.

Transaction is one of the reserved names in SQLite. For a full list see here.
Ways to solve this issue are:
Change the Table name to a word that isn't reserved.
or
Quote the reserved name by using one of these 4 listed quote marks
'keyword'
"keyword"
[keyword]
`keyword`

Related

why i am keep getting an SQL syntax error? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'm trying to execute a simple MySQL query as below:
INSERT INTO user_details (username, location, key)
VALUES ('Tim', 'Florida', 42)
But I'm getting the following error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES ('Tim', 'Florida', 42)' at line 1
How can I fix the issue?
The Problem
In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("`"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
ADD
AND
BEFORE
BY
CALL
CASE
CONDITION
DELETE
DESC
DESCRIBE
FROM
GROUP
IN
INDEX
INSERT
INTERVAL
IS
KEY
LIKE
LIMIT
LONG
MATCH
NOT
OPTION
OR
ORDER
PARTITION
RANK
REFERENCES
SELECT
TABLE
TO
UPDATE
WHERE
The Solution
You have two options.
1. Don't use reserved words as identifiers
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
2. Use backticks
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT);
Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^

operational error when updating sqlite3 record using Tkinter python [duplicate]

I'm trying out statements for creating a database, and after 10 entities without any issues I ran into this error
Error: Near line 83: near "Transaction": syntax error
The first line is line 83 with it's context of creating a table
CREATE TABLE Transaction (
TransactionID INTEGER,
AccountID INTEGER REFERENCES User (AccountID),
ItemID INTEGER REFERENCES Item (ItemID),
Method STRING,
Price INTEGER,
TransactionDate DATE,
PRIMARY KEY (TransactionID)
);
Now I can't seem to find the issue, and suggestion's of something with ASCII using the wrong space couldn't be solved by writing the same thing again manually.
I haven't even gotten around to checking the integrity of my foreign keys, and it's not working. Hopefully somebody could provide some insight on what I'm missing.
Transaction is one of the reserved names in SQLite. For a full list see here.
Ways to solve this issue are:
Change the Table name to a word that isn't reserved.
or
Quote the reserved name by using one of these 4 listed quote marks
'keyword'
"keyword"
[keyword]
`keyword`

Python/MySQL: "Truncated incorrect double value..." on a simple text insert

I've got a problem with a presumably simple text insert into a MySQL database from Python. The text is a HTML string, with which I want to update an existing row based on this rows primary key. I'm using this statement with PyMySQL (line breaks added for readability):
cursor.execute("UPDATE my_table SET my_text_col = %s
AND another_int_col = %s WHERE my_table_pk_col = %s",
(some_html_string, some_int, this_rows_pk))
This should be fairly straightforward, but (as way to often with MySQL) it apparently isn't. I get
Warning: (1292, Truncated incorrect DOUBLE value: [Beginning of some_html_string])
and the my_text_col is set to 0.
I have no idea why this doesn't work. There is no double field in this table, the HTML is a string that gets properly escaped, the other two values are ints. I have seen that others reported similar issues, and there are even bug reports related to this (#43437, #46641), but these are more than 8 years old and haven't been fixed (I'm using MySQL 5.6.27 and PyMySQL 0.7.11).
If anyone has solution or a workaround to get this simple update done I would greatly appreciate it.
That's a simple but not obvious syntax error:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
This is the syntax from the docs (https://dev.mysql.com/doc/refman/5.7/en/update.html), multiple fields are seperated with commas not with AND in update statements.

Python , MYSQL database

i have a table that records the attendance of students. The table have 4 columns , one for the student ID and the other are for week1 ,week2 and week3 (All the columns are integers). The attendance is recorded by entering only 1 for the certain week ( or zero if he was absent) . My problem is here , when i want to add the attendance i use the update statement as follow :
week_number=input('enter the week ( week1/week2/week3')
id=int(input('enter student ID'))
sat="UPDATE Attendance2 SET %s=1 WHERE ID=%s "
cur.execute(sat, (week_number,id,))
conn.commit()
As you can see ,I don't know what the column that the user will refer to ( it is a variable ) , so i have used %s behind the SET, but it is wrong.
Here is the error :
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''week1'=1 WHERE ID=300' at line 1
Any help please ? How do i write a variable column name in a execute statement ?
Note that i am updating only the attended students , that's why there is 1 in the UPDATE statement
AFAICT, it's supposed to be ok to surround keys with quotes. But as you say that all datatypes are integers, your values have no issues.
And because it says this is a syntax error (and not column issue, what it would yell if it was not finding week1), it leads me to believe the issues actually are your quotes, which if not expected by mysql's SQL grammar, it would indeed yell about a syntax issue.
mysql […] near ''week1'=1 WHERE ID=300' at line 1
^
What makes a python string gets surrounded by single quotes? It's the repr() version of the string, the one you get when you type a string on the REPL:
>>> x = '42'
>>> x
'42'
>>> print(repr(x))
'42'
>>> print(x)
42
I'm not sure why this issue would happen to you. A good ideais to use the python form of formatting strings, and run:
sat="UPDATE Attendance2 SET {}=1 WHERE ID={}".format(week_number, id)
if it still happens, you can try to force typing of week_number into a str(), using str(week_number).
Talking about formatting strings, you might want to enforce the typing, so you avoid surprises:
sat="UPDATE Attendance2 SET {:s}=1 WHERE ID={:d}".format(str(week_number), int(id))
which will make sure week_number is a valid string and formatted as a string, and id is a valid integer and formatted as an integer.
Nota Bene: avoid using id in your code, which is a python reserved keyword, and instead use _id, ident or idx. It's always a good idea to avoid shadowing global python keywords.
HTH
try
sat="UPDATE Attendance2 SET " + week_number + "='1' WHERE ID='" + student_id + "'"
cur.execute(sat)
...
hope this helps ^^-d
PS: It is easier to test the code if you set the variables week_number and student_id "hardwired", e.g.:
week_number = "week1"
student_id = "1"
PPS: The way you design your table is a bit redundant which may lead to update errors in the future. It might e.g. be better to have a 2 column table with the student_id and attended_week(as 1,2,3).

Insert into sqlite3 a null date from pyramid framework using sqlalchemy

python 2.7
pyramid 1.3a4
sqlalchemy 7.3
sqlite3.7.9
from sqlite prompt > I can do:
insert into risk(travel_dt) values ('')
also
insert into risk(travel_dt) values(Null)
Both result in a new row with a null value for risk.travel_dt but when I try those travel_dt values from pyramid, Sqlalchemy gives me an error.
In the first case, I get sqlalchemy.exc.StatementError:
SQLite Date type only accepts python date objects as input
In the second case, I get Null is not defined. When I use "Null", I get the first case error
I apologize for another question on nulls: I have read a lot of material but must have missed something simple. Thanks for any help
Clemens Herschel
While you didn't provide any insight into the table definition you're using or any example code, I am guessing the issue is due to confusing NULL (the database reserved word) and None (the Python reserved word).
The error message is telling you that you need to call your SQLA methods with valid python date objects, rather than strings such as "Null" or ''.
Assuming you have a Table called risk containing a Column called travel_dt, you should be able to create a row in that table with something sort of like:
risk.insert().values(travel_dt=None)
Note that this is just a snippet, you would need to execute such a call within an engine context like that defined in the SA Docs SQL Expression Language Tutorial.

Categories