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)")
Related
I am trying to create a database using python to execute the SQL commands (for CS50x problem set 7).
I have created a table with an id field set to AUTO_INCREMENT, but the field in the database is populated only by NULL values. I just want it to have an incrementing id starting at 1.
I've tried searching online to see if I'm using the right syntax and can't find anything obvious, nor can I find someone else with a similar problem, so any help would be much appreciated.
Here is the SQL command I am running:
# For creating the table
db.execute("""
CREATE TABLE students (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
middle_name VARCHAR(255) DEFAULT (NULL),
last_name VARCHAR(255) NOT NULL,
house VARCHAR(10),
birth INTEGER
);
""")
# An example insert statement
db.execute("""
INSERT INTO students (
first_name,
middle_name,
last_name,
house,
birth
)
VALUES (
?, ?, ?, ?, ?
);
""", "Harry", "James", "Potter", "Gryffindor", 1980)
Here is a screenshot of the database schema shown in phpliteadmin :
And here is a screenshot of the resulting database:
My guess is that you are using SQLite with phpliteadmin and not MySql, in which case this:
id INTEGER AUTO_INCREMENT PRIMARY KEY
is not the correct definition of the auto increment primary key.
In fact, the data type of this column is set to INTEGER AUTO_INCREMENT, as you can see in phpliteadmin, which according to 3.1. Determination Of Column Affinity, has INTEGER affinity.
Nevertheless it is the PRIMARY KEY of the table but this allows NULL values.
The correct syntax to have an integer primary key is this:
id INTEGER PRIMARY KEY AUTOINCREMENT
This cannot happen, if your statements are executed correctly.
I notice that you are not checking for errors in your code. You should be doing that!
My guess is that the table is already created without the auto_increment attribute. The create table is generating an error and you are inserting into the older version.
You can fix this by dropping the table before you create it. You should also modify the code to check for errors.
how to block the possibility of adding the same values to the database, for example e-mail addresses in python and MySQL?
From database perspective, you would typically put a unique constraint on the corresponding table column:
create table users (
id int auto_increment primary key,
name varchar(50) not null,
email varchar(100) not null unique
);
With this set up in place, any query that would attempt generating a duplicate email (either from an INSERT or an UPDATE) would fail with a unique contraint violation error.
I've finished making some SQLite tables and am executing the instructions. When executing the instructions, the following error has come up:
sqlite3.OperationalError: near "Category": syntax error
Most of my tables use the same sort of format, below is an example of one such table.
CategoryTableSQL = """ CREATE TABLE IF NOT EXISTS Category(
CategoryID integer PRIMARY KEY AUTOINCREMENT
Category text NOT NULL
);"""
databaseNewTable(Connection, CategoryTableSQL)
You forgot a comma between the declaration of your table fields in your SQL-statement: It should be like this. Always use comma's to seperate the field-creation statements. Except of course, for the last field you create =). Also, I would take care in naming your fields the same name as your tables. To prevent confusion. Just my two cents
CREATE TABLE IF NOT EXISTS Category(
CategoryID integer PRIMARY KEY AUTOINCREMENT,
Category text NOT NULL
);
I think, You just need to add the ',' symbol after the AUTOINCREMENT word. :-)
Like this:
CategoryTableSQL = """ CREATE TABLE IF NOT EXISTS Category(
CategoryID integer PRIMARY KEY AUTOINCREMENT,
Category text NOT NULL
);"""
databaseNewTable(Connection, CategoryTableSQL)
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'), ...
Im using a table constraint to create a composite primary key, I would like the id field to autoincrement, is this possible? or what are the alternatives?
CREATE TABLE IF NOT EXISTS atable(
id INTEGER NOT NULL, --I want to autoincrement this one
name TEXT NOT NULL,
anotherCol TEXT,
PRIMARY KEY(id, name));
No, there's only one primary key: that's the composite of id and name.
If you mean that you want id to be the primary key, and name to be an indexed alternate key, I'd say that you should give name a unique constraint and make id the primary key.
Here's the link to the SQLite FAQ page where your question of how to autoincrement an integer primary key is #1. http://www.sqlite.org/faq.html#q1
Here's your SQL reworked a little:
CREATE TABLE IF NOT EXISTS atable(
id INTEGER PRIMARY KEY, -- use NULL for this column on INSERT to autoinc
name TEXT NOT NULL,
anotherCol TEXT);
then create a unique index on NAME as suggested by duffymo and Kaleb.
It doesn't look to me that the OP want names to be unique. (But I could be wrong.) At any rate, you can
get an autoincrementing integer by using INTEGER PRIMARY KEY and inserting NULL into that column, and
declare a superkey by using a UNIQUE constraint on (id, name).
A superkey is just a candidate key (primary key in this case) plus one or more columns.
CREATE TABLE yourtable(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
CONSTRAINT superkey UNIQUE (id, name)
);
If you turn on foreign key support using PRAGMA foreign_keys = on;, the superkey can be the target of foreign key constraints in other tables. But I'm not certain that's what you were looking for.