This is my code:
conn.execute("""
CREATE TABLE IF NOT EXISTS Blockchain_transactions(
hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
id INTEGER DEFAULT NULL,
transaction CHAR DEFAULT NULL
);""")
It generates a syntax error
sqlite3.OperationalError: near "transaction": syntax error
REMARK: This comes earlier in my code and does not generate the same error
conn.execute("""
CREATE TABLE IF NOT EXISTS Blockchain_blocks (
hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
proof_of_work INTEGER DEFAULT NULL,
difficulty INTEGER DEFAULT NULL
);""")
transaction is a sqlite keyword.
Change the column name to something different and it will work.
Avoid reserved keywords for column names, or escape them like this:
conn.execute("""
CREATE TABLE IF NOT EXISTS Blockchain_transactions(
hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
id INTEGER DEFAULT NULL,
`transaction` CHAR DEFAULT NULL
);""")
Other possibilities to escape / quote keywords can be found in the linked keywords page.
Related
I'm basically building a secured online diary application with Flask. However my Python source code returns a syntax error when I try to test the app. I can't detect what's wrong with the syntax. Your help will be appreciated.
I'm attaching a screenshot of the error. And here's my SQL database's schema:
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT NOT NULL,
hash TEXT NOT NULL
);
CREATE TABLE sqlite_sequence(name,seq);
CREATE UNIQUE INDEX username ON users (username);
CREATE TABLE diaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT NOT NULL,
time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
description TEXT NOT NULL,
img_url TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
);
New error: unsupported value
It is INSERT statement that causes error.
Well, not the insert itself but the way you're using it.
Values should be passed as a tuple (values between "(" and ")")
So, you need to update db.execute line with something like that
db.execute("insert into table_name(col1, col2) values(?, ?)", (col1_val, col2_val))
UPD. regarding the error on second screenshot.
db.execute("Select...) does not return a value but a set of values.
So, you might wanted to use fetchone() as in docs
res = cur.execute('SELECT count(rowid) FROM stocks') # gets you set records
print(res.fetchone()) # get first record
Anyway, check the docs I provided you link to with.
I am trying to create a number of tables with different names (of course) but sharing the same schema. For this purpose, I am using executemany on a Cursor object as follows:
tables = ['Meanings', 'Synonyms', 'Antonyms', 'Examples', 'Phrases',
'Pronunciations', 'Hyphenations']
create_table_query = '''CREATE TABLE (?) (
id INTEGER NOT NULL,
text TEXT,
word_id INTEGER NOT NULL,
PRIMARY KEY id,
FOREIGN KEY(word_id) REFERENCES Word(id)
)'''
cursor.executemany(create_table_query, tables)
When I execute this snippet, I get the following error message:
OperationalError: near "(": syntax error
I am having trouble fixing the bug here with my SQL since I find the error message to be not descriptive enough. I have tried the following queries but I am unable to develop the understanding of their success and my query's failure:
create_table_query_1 = '''CREATE TABLE {} (
id INTEGER NOT NULL,
text TEXT,
word_id INTEGER NOT NULL,
PRIMARY KEY id,
FOREIGN KEY(word_id) REFERENCES Word(id)
)''' # Syntax error near "id"
create_table_query_2 = '''CREATE TABLE (?) (
id INTEGER PRIMARY KEY,
text TEXT,
word_id INTEGER NOT NULL,
FOREIGN KEY(word_id) REFERENCES Word(id)
)''' # Syntax error near "("
create_table_query_1 = '''CREATE TABLE {} (
id INTEGER PRIMARY KEY,
text TEXT,
word_id INTEGER NOT NULL,
FOREIGN KEY(word_id) REFERENCES Word(id)
)''' # works with string formatting
Also, what are other efficient(in terms of time) ways to achieve the same?
To put my comment into an answer and expand on it: you cannot parametrize table nor column names. I was unable to find any documentation on this...
In a couple of the other examples you have extra parens/brackets that SQLite doesn't need.
So the solution, as you've found, is to use string substitution for the table names as in your final example.
Here's an example with a loop over all of your tables:
for table in tables:
cursor.execute('''CREATE TABLE {} (
id INTEGER PRIMARY KEY,
text TEXT,
word_id INTEGER NOT NULL,
FOREIGN KEY(word_id) REFERENCES Word(id)
)'''.format(table))
I am not completely clear on why you want different tables for the different types of words, though, as this would seem to go against the principles of database design.
I am trying to iterate through a JSON object and save that information into Django fields and have had pretty good success so far. However when processing data from foreign countries I am having problems ignoring special characters.
a simplified version of the code block in customers.views is below:
customer_list = getcustomers() #pulls standard JSON object
if customer_list:
for mycustomer in customer_list:
entry = Customer(pressid=mycustomer['id'],
email = mycustomer['email'],
first_name = mycustomer['first_name']
)
The code above works great... until you introduce a foreign character, say a name with non-utf-8 charset.
An example error is:
Warning at /customers/update/
Incorrect string value: '\xC4\x97dos' for column 'first_name' at row 1
I have tried adding the .encode('utf-8') to the end of strings, but I still get this error, and haven't found a way to avoid it. I am okay with truncation of data in a particular field if it uses invalid characters, but I can't make a list of all possible characters because next thing you know a new customer will use a letter I didn't know existed.
Thanks in advance for the help!
Your databes is not configurated correctly.
https://docs.djangoproject.com/en/1.7/ref/unicode/
For example table like that:
CREATE TABLE IF NOT EXISTS `api_projekt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nazwa` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nazwa` (`nazwa`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
Will raise error when you try add non-ASCII character. You need to change encoding from latin1 to utf-8.
It should look:
CREATE TABLE IF NOT EXISTS `api_projekt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nazwa` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nazwa` (`nazwa`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
To fix it:
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
I had a look at the unicode python documents, and found a line that appears to be solving things https://docs.python.org/2/howto/unicode.html.
I added .encode('ascii', 'ignore') instead of .encode(utf-8) and it is now working on all values.
This method truncates all unknown characters, and it is the best I could come up with.
I have a table in my PostgreSQL:
CREATE SEQUENCE dember_id_seq INCREMENT BY 1 MINVALUE 1 START 1;
CREATE TABLE dember (id INT NOT NULL, did VARCHAR(255) DEFAULT NULL, dnix VARCHAR(255) DEFAULT NULL, durl TEXT DEFAULT NULL, created TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, modified TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, status BOOLEAN NOT NULL, dnickname VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id));
When I want to insert a record, I using the following code:
import pg
db = pg.DB(....)
db.insert('dember',{'did':did,'dnix':dnix,'durl',durl,'created',now, 'modified':now, 'status':'true','dnickname':nickname'})
Then the insert code does not work, I get the following error:
pg.ProgrammingError: ERROR: null value in column "id" violates not-null constraint
It looks that I have to add {'id':number} to the value dictionary.
Any suggestions? Thanks.
You should save yourself some trouble and use serial instead of int:
The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).
So saying:
create table t (
id serial not null primary key
-- ...
)
will create id as an integer column, create a sequence for it, set the default value of id to be the next value in the sequence, and set the sequence's owner to the id column; the last bit is important, the implied
ALTER SEQUENCE t_id_seq OWNED BY t.id;
that a serial type does ensures that the sequence will be dropped when the column goes away. If you don't set the sequence's owner, you can be left with dangling unused sequences in your database.
You forgot to assign the sequence to the column.
CREATE TABLE dember (id INT NOT NULL DEFAULT nextval('dember_id_seq'), ...
I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page http://www.sqlite.org/syntaxdiagrams.html#column-constraint but that did not work either. Without AUTO_INCREMENT my table can be created.
An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
This is addressed in the SQLite FAQ. Question #1.
Which states:
How do I create an AUTOINCREMENT
field?
Short answer: A column declared
INTEGER PRIMARY KEY will
autoincrement.
Here is the long answer: If you
declare a column of a table to be
INTEGER PRIMARY KEY, then whenever you
insert a NULL into that column of the
table, the NULL is automatically
converted into an integer which is one
greater than the largest value of that
column over all other rows in the
table, or 1 if the table is empty. (If
the largest possible integer key,
9223372036854775807, then an unused
key value is chosen at random.) For
example, suppose you have a table like
this:
CREATE TABLE t1( a INTEGER PRIMARY
KEY, b INTEGER ); With this table,
the statement
INSERT INTO t1 VALUES(NULL,123); is
logically equivalent to saying:
INSERT INTO t1 VALUES((SELECT max(a)
FROM t1)+1,123); There is a function
named sqlite3_last_insert_rowid()
which will return the integer key for
the most recent insert operation.
Note that the integer key is one
greater than the largest key that was
in the table just prior to the insert.
The new key will be unique over all
keys currently in the table, but it
might overlap with keys that have been
previously deleted from the table. To
create keys that are unique over the
lifetime of the table, add the
AUTOINCREMENT keyword to the INTEGER
PRIMARY KEY declaration. Then the key
chosen will be one more than than the
largest key that has ever existed in
that table. If the largest possible
key has previously existed in that
table, then the INSERT will fail with
an SQLITE_FULL error code.
It looks like AUTO_INCREMENT should be AUTOINCREMENT see http://www.sqlite.org/syntaxdiagrams.html#column-constraint
You could try
CREATE TABLE fileInfo
(
fileid INTEGER PRIMARY KEY AUTOINCREMENT,
name STRING,
status INTEGER NOT NULL
);
We just changed the order from
NOT NULL, AUTO_INCREMENT
to
AUTO_INCREMENT NOT NULL,
an example :
cursor.execute("CREATE TABLE users(\
user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
user_name VARCHAR(100) NOT NULL)")