'sqlite3.OperationalError: near ")": syntax error' while creating a table [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to make a stock program for my neighborhood and, I am trying to run this code:
def create_tables():
c.execute('CREATE TABLE IF NOT EXISTS products(cod INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, bar_code INTEGER, '\
'descr VARCHAR(100) NOT NULL, quant_stock REAL, type_un TEXT, cost_un REAL, value_un REAL NOT NULL, fab_date TEXT, '\
'due_date TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
'descr TEXT PRIMARY KEY NOT NULL, value_un REAL NOT NULL, type_un TEXT, quant_stock REAL NOT NULL, '\
'tot_value REAL NOT NULL, sell_date TEXT NOT NULL, FOREIGN KEY (cod) REFERENCES products(cod)')
c.execute('CREATE TABLE IF NOT EXISTS purchase(cod INTEGER FOREIGN KEY, bar_code INTEGER, '\
'descr TEXT NOT NULL, cost_un REAL, type_un TEXT, pur_quant REAL NOT NULL, tot_cost REAL NOT NULL, '\
'pur_date TEXT NOT NULL, fab_date TEXT, due_date TEXT')
And I get this error:
File "app.py", line 17, in create_tables
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
sqlite3.OperationalError: near ")": syntax error
I have no idea why this happens, because the first table is created with no problems (I already commented the two others and the script ran normally). Could anyone help me please?

You're missing a closing bracket in your second and third table inserts:
def create_tables():
c.execute('CREATE TABLE IF NOT EXISTS products(cod INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, bar_code INTEGER, '\
'descr VARCHAR(100) NOT NULL, quant_stock REAL, type_un TEXT, cost_un REAL, value_un REAL NOT NULL, fab_date TEXT, '\
'due_date TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS sells(cod INTEGER NOT NULL, bar_code INTEGER, '\
'descr TEXT PRIMARY KEY NOT NULL, value_un REAL NOT NULL, type_un TEXT, quant_stock REAL NOT NULL, '\
'tot_value REAL NOT NULL, sell_date TEXT NOT NULL, FOREIGN KEY (cod) REFERENCES products(cod))')
c.execute('CREATE TABLE IF NOT EXISTS purchase(cod INTEGER FOREIGN KEY, bar_code INTEGER, '\
'descr TEXT NOT NULL, cost_un REAL, type_un TEXT, pur_quant REAL NOT NULL, tot_cost REAL NOT NULL, '\
'pur_date TEXT NOT NULL, fab_date TEXT, due_date TEXT)')

Related

SQLITE3.OperationalError: near ")": syntax error when creating database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I can't seem to be able to see for myself, what when wrong in this line of codes, have been staring at it for the last 20 min but I can't seem to figure anything out.
here is the error:
Traceback (most recent call last):
File "C:\Users\usera\PycharmProjects\itptesting_2\itptesting\init_db.py", line 7, in <module>
connection.executescript(f.read()),
sqlite3.OperationalError: near ")": syntax error
and the fullcode:
import sqlite3
connection = sqlite3.connect('database.db')
with open('schema.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('First Post', 'Content for the first post')
)
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('Second Post', 'Content for the second post')
)
cur.execute("INSERT INTO users (fullname, email, password) VALUES (?, ?, ?)",
('UserA', 'user#demo.com', 'asdfghjkl')
)
cur.execute("INSERT INTO entries (stockname, partnum, company, quantity, uom, remarks) VALUES (?, ?, ?, ?, ?, ?)",
('Beer','Albee0001','RES','24','BTL','new stock for promotions ')
)
connection.commit()
connection.close()
and schema.sql
DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
content TEXT NOT NULL
);
DROP TABLE IF EXISTS signup;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fullname TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
);
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded NOT NULL DEFAULT CURRENT_TIMESTAMP,
remarks TEXT NULL,
FOREIGN KEY(id) REFERENCES users(id),
);
I had tried deleting the database.db file and regenerating it by run init_db.py but it still gave me the same error. What should I do?
You have a couple of problems, this is the correct syntax:
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded DATE NOT NULL DEFAULT (CURRENT_TIMESTAMP),
remarks TEXT,
FOREIGN KEY(id) REFERENCES users(id)
);

Using Python, export SQLite schema

In the SQLite command line, the command .schema can be used to export a database schema in SQL syntax, and that export can be used to rebuild a database of the same structure:
.output folderpath/schema.sql
.schema
Saves the following to a file named "schema.sql":
CREATE TABLE mytable (id INTEGER NOT NULL, name TEXT NOT NULL, date DATETIME, PRIMARY KEY (id), FOREIGN KEY (name) REFERENCES mytable2 (na ...
Can the same output .sql file be achieved using Python's sqlite3 library without a custom function?
There are several questions on Stack Overflow with similar titles, but I didn't find any that are actually trying to get the full schema (they are actually looking for PRAGMA table_info which does not have the CREATE TABLE, etc. statements in the output).
Well. Rewritten the answer above. It that exactly what you need?
import sqlite3
dbname = 'chinook.db'
with sqlite3.connect(dbname) as con:
cursor = con.cursor()
cursor.execute('select sql from sqlite_master')
for r in cursor.fetchall():
print(r[0])
cursor.close()
With the test sqlite3 database I received the following:
CREATE TABLE "albums"
(
[AlbumId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Title] NVARCHAR(160) NOT NULL,
[ArtistId] INTEGER NOT NULL,
FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE sqlite_sequence(name,seq)
CREATE TABLE "artists"
(
[ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "customers"
(
[CustomerId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[FirstName] NVARCHAR(40) NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[Company] NVARCHAR(80),
[Address] NVARCHAR(70),
[City] NVARCHAR(40),
[State] NVARCHAR(40),
[Country] NVARCHAR(40),
[PostalCode] NVARCHAR(10),
[Phone] NVARCHAR(24),
[Fax] NVARCHAR(24),
[Email] NVARCHAR(60) NOT NULL,
[SupportRepId] INTEGER,
FOREIGN KEY ([SupportRepId]) REFERENCES "employees" ([EmployeeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "employees"
(
[EmployeeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[FirstName] NVARCHAR(20) NOT NULL,
[Title] NVARCHAR(30),
[ReportsTo] INTEGER,
[BirthDate] DATETIME,
[HireDate] DATETIME,
[Address] NVARCHAR(70),
[City] NVARCHAR(40),
[State] NVARCHAR(40),
[Country] NVARCHAR(40),
[PostalCode] NVARCHAR(10),
[Phone] NVARCHAR(24),
[Fax] NVARCHAR(24),
[Email] NVARCHAR(60),
FOREIGN KEY ([ReportsTo]) REFERENCES "employees" ([EmployeeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "genres"
(
[GenreId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "invoices"
(
[InvoiceId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[CustomerId] INTEGER NOT NULL,
[InvoiceDate] DATETIME NOT NULL,
[BillingAddress] NVARCHAR(70),
[BillingCity] NVARCHAR(40),
[BillingState] NVARCHAR(40),
[BillingCountry] NVARCHAR(40),
[BillingPostalCode] NVARCHAR(10),
[Total] NUMERIC(10,2) NOT NULL,
FOREIGN KEY ([CustomerId]) REFERENCES "customers" ([CustomerId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "invoice_items"
(
[InvoiceLineId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[InvoiceId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
[UnitPrice] NUMERIC(10,2) NOT NULL,
[Quantity] INTEGER NOT NULL,
FOREIGN KEY ([InvoiceId]) REFERENCES "invoices" ([InvoiceId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "media_types"
(
[MediaTypeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "playlists"
(
[PlaylistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "playlist_track"
(
[PlaylistId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
CONSTRAINT [PK_PlaylistTrack] PRIMARY KEY ([PlaylistId], [TrackId]),
FOREIGN KEY ([PlaylistId]) REFERENCES "playlists" ([PlaylistId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
None
CREATE TABLE "tracks"
(
[TrackId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(200) NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2) NOT NULL,
FOREIGN KEY ([AlbumId]) REFERENCES "albums" ([AlbumId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES "genres" ([GenreId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES "media_types" ([MediaTypeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE INDEX [IFK_AlbumArtistId] ON "albums" ([ArtistId])
CREATE INDEX [IFK_CustomerSupportRepId] ON "customers" ([SupportRepId])
CREATE INDEX [IFK_EmployeeReportsTo] ON "employees" ([ReportsTo])
CREATE INDEX [IFK_InvoiceCustomerId] ON "invoices" ([CustomerId])
CREATE INDEX [IFK_InvoiceLineInvoiceId] ON "invoice_items" ([InvoiceId])
CREATE INDEX [IFK_InvoiceLineTrackId] ON "invoice_items" ([TrackId])
CREATE INDEX [IFK_PlaylistTrackTrackId] ON "playlist_track" ([TrackId])
CREATE INDEX [IFK_TrackAlbumId] ON "tracks" ([AlbumId])
CREATE INDEX [IFK_TrackGenreId] ON "tracks" ([GenreId])
CREATE INDEX [IFK_TrackMediaTypeId] ON "tracks" ([MediaTypeId])
CREATE TABLE sqlite_stat1(tbl,idx,stat)

MySQL datetime column WHERE col IS NULL fails

I cannot get my very basic SQL query to work as it returns 0 values despite the fact that there are clearly nulls
query
SELECT
*
FROM
leads AS l
JOIN closes c ON l.id = c.lead_id
WHERE
c.close_date IS NULL
DDL
CREATE TABLE closes
(
id INT AUTO_INCREMENT
PRIMARY KEY,
lead_id INT NOT NULL,
close_date DATETIME NULL,
close_type VARCHAR(255) NULL,
primary_agent VARCHAR(255) NULL,
price FLOAT NULL,
gross_commission FLOAT NULL,
company_dollar FLOAT NULL,
address VARCHAR(255) NULL,
city VARCHAR(255) NULL,
state VARCHAR(10) NULL,
zip VARCHAR(10) NULL,
CONSTRAINT closes_ibfk_1
FOREIGN KEY (lead_id) REFERENCES leads (id)
)
ENGINE = InnoDB;
CREATE INDEX lead_id
ON closes (lead_id);
I should mention that I am inserting the data with a python web scraper and SQLAlchemy. If the data is not scraped it will be None on insert.
Here is a screenshot of datagrip showing a null value in the row
EDIT
Alright so I went ahead and ran the following on some of the entries in the table where the value was already <null>
UPDATE closes
SET close_date = NULL
WHERE
lead_id = <INTEGERVAL>
;
What is interesting now is that when running the original query I do actually return the 2 records that I ran the update query for (the expected outcome). This would lead me to believe that the issues is with how my SQLAlchemy model is mapping the values on insert.
models.py
class Close(db.Model, ItemMixin):
__tablename__ = 'closes'
id = db.Column(db.Integer, primary_key=True)
lead_id = db.Column(db.Integer, db.ForeignKey('leads.id'), nullable=False)
close_date = db.Column(db.DateTime)
close_type = db.Column(db.String(255))
primary_agent = db.Column(db.String(255))
price = db.Column(db.Float)
gross_commission = db.Column(db.Float)
company_dollar = db.Column(db.Float)
address = db.Column(db.String(255))
city = db.Column(db.String(255))
state = db.Column(db.String(10))
zip = db.Column(db.String(10))
def __init__(self, item):
self.build_from_item(item)
def build_from_item(self, item):
for k, v in item.items():
setattr(self, k, v)
But I am fairly confident the value is a python None in the event no value is scraped from the website. My understanding is that SQLAlchemy would map a None to NULL on insert and given that nullable=True is the default setting, which can seen on the generated DDL, I am still at a loss as to why it appears to be NULL when in reality it is not behaving that way.
EDIT 2
Only place where I think the issue would be happening is where my spider actually scrapes the data and assigns it to the Item which is shown below
closes.py
# item['close_date'] = None at this point
try:
item['close_date'] = arrow.get(item['close_date'], 'MMM D, YYYY').format('YYYY-MM-DD')
except ParserError as e:
# Maybe item['close_date'] = None here?
spider.logger.error(f'Parse error: {item["close_date"]} - {e}')
In the python code I've written this would appear to be the place where the issue would arise. But if arrow.get throws an exception the value of item['close_date'] should still be None. If that is not the case and even if it is it does not explain why it appears that the record value is NULL even thought it does not behave like it is.
I'm guessing that you're having an issue with the join, not the NULL value. The query below returns 1 result for me. More info about your data, the software used for querying (I tested with SQL Yog), and applicable versions might help.
EDIT
It could be that you're having issues with MySQL's 'zero date'.
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html
MySQL permits you to store a “zero” value of '0000-00-00' as a “dummy
date.” This is in some cases more convenient than using NULL values,
and uses less data and index space. To disallow '0000-00-00', enable
the NO_ZERO_DATE mode.
I've updated the SQL data below to include a zero date in the INSERT and SELECT's WHERE.
DROP TABLE IF EXISTS closes;
DROP TABLE IF EXISTS leads;
CREATE TABLE leads (
id INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO leads(id) VALUES (1),(2),(3);
CREATE TABLE closes (
id INT(11) NOT NULL AUTO_INCREMENT,
lead_id INT(11) NOT NULL,
close_date DATETIME DEFAULT NULL,
close_type VARCHAR(255) DEFAULT NULL,
primary_agent VARCHAR(255) DEFAULT NULL,
price FLOAT DEFAULT NULL,
gross_commission FLOAT DEFAULT NULL,
company_dollar FLOAT DEFAULT NULL,
address VARCHAR(255) DEFAULT NULL,
city VARCHAR(255) DEFAULT NULL,
state VARCHAR(10) DEFAULT NULL,
zip VARCHAR(10) DEFAULT NULL,
PRIMARY KEY (id),
KEY lead_id (lead_id),
CONSTRAINT closes_ibfk_1 FOREIGN KEY (lead_id) REFERENCES leads (id)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
INSERT INTO closes(id,lead_id,close_date,close_type,primary_agent,price,gross_commission,company_dollar,address,city,state,zip)
VALUES
(1,3,'0000-00-0000',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(3,2,'2018-01-09 17:01:44',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
SELECT
*
FROM
leads AS l
JOIN closes c ON l.id = c.lead_id
WHERE
c.close_date IS NULL OR c.close_date = '0000-00-00';

SQLite3 DatabaseError: malformed database schema

Trying to run sydent on Debian Jessie using SQLite version 3.18.0, but receiving an error.
(sydent)gooseberry#servername:/opt/sydent# python -m sydent.sydent
INFO:sydent.db.sqlitedb:Using DB file sydent.db
WARNING:sydent.http.httpcommon:No HTTPS private key / cert found: not starting replication server or doing replication pushes
INFO:sydent.http.httpserver:Starting Client API HTTP server on port 8090
INFO:twisted:Site starting on 8090
INFO:twisted:Starting factory <twisted.web.server.Site instance at 0x7fda3b6c2950>
Unhandled error in Deferred:
CRITICAL:twisted:Unhandled error in Deferred:
CRITICAL:twisted:
Traceback (most recent call last):
File "/opt/sydent/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File "/opt/sydent/local/lib/python2.7/site-packages/sydent/replication/pusher.py", line 76, in scheduledPush
peers = self.peerStore.getAllPeers()
File "/opt/sydent/local/lib/python2.7/site-packages/sydent/db/peers.py", line 52, in getAllPeers
res = cur.execute("select p.name, p.port, p.lastSentVersion, pk.alg, pk.key from peers p, peer_pubkeys pk "
DatabaseError: malformed database schema (medium_lower_address) - near "(": syntax error
^CINFO:twisted:Received SIGINT, shutting down.
below is the output from select * from sqlite_master;
table|invite_tokens|invite_tokens|2|CREATE TABLE invite_tokens (
id integer primary key,
medium varchar(16) not null,
address varchar(256) not null,
room_id varchar(256) not null,
sender varchar(256) not null,
token varchar(256) not null,
received_ts bigint, -- When the invite was received by us from the homeserver
sent_ts bigint -- When the token was sent by us to the user
)
index|invite_token_medium_address|invite_tokens|3|CREATE INDEX invite_token_medium_address on invite_tokens(medium, address)
index|invite_token_token|invite_tokens|4|CREATE INDEX invite_token_token on invite_tokens(token)
table|ephemeral_public_keys|ephemeral_public_keys|5|CREATE TABLE ephemeral_public_keys(
id integer primary key,
public_key varchar(256) not null,
verify_count bigint default 0,
persistence_ts bigint
)
index|ephemeral_public_keys_index|ephemeral_public_keys|6|CREATE UNIQUE INDEX ephemeral_public_keys_index on ephemeral_public_keys(public_key)
table|peers|peers|7|CREATE TABLE peers (id integer primary key, name varchar(255) not null, port integer default null, lastSentVersion integer, lastPokeSucceededAt integer, active integer not null default 0)
index|name|peers|8|CREATE UNIQUE INDEX name on peers(name)
table|peer_pubkeys|peer_pubkeys|9|CREATE TABLE peer_pubkeys (id integer primary key, peername varchar(255) not null, alg varchar(16) not null, key text not null, foreign key (peername) references peers (peername))
index|peername_alg|peer_pubkeys|10|CREATE UNIQUE INDEX peername_alg on peer_pubkeys(peername, alg)
table|threepid_validation_sessions|threepid_validation_sessions|11|CREATE TABLE threepid_validation_sessions (id integer primary key, medium varchar(16) not null, address varchar(256) not null, clientSecret varchar(32) not null, validated int default 0, mtime bigint not null)
table|threepid_token_auths|threepid_token_auths|12|CREATE TABLE threepid_token_auths (id integer primary key, validationSession integer not null, token varchar(32) not null, sendAttemptNumber integer not null, foreign key (validationSession) references threepid_validations(id))
table|local_threepid_associations|local_threepid_associations|13|CREATE TABLE local_threepid_associations (id integer primary key, medium varchar(16) not null, address varchar(256) not null, mxid varchar(256) not null, ts integer not null, notBefore bigint not null, notAfter bigint not null)
index|medium_address|local_threepid_associations|14|CREATE UNIQUE INDEX medium_address on local_threepid_associations(medium, address)
table|global_threepid_associations|global_threepid_associations|15|CREATE TABLE global_threepid_associations (id integer primary key, medium varchar(16) not null, address varchar(256) not null, mxid varchar(256) not null, ts integer not null, notBefore bigint not null, notAfter integer not null, originServer varchar(255) not null, originId integer not null, sgAssoc text not null)
index|medium_lower_address|global_threepid_associations|16|CREATE INDEX medium_lower_address on global_threepid_associations (medium, lower(address))
index|originServer_originId|global_threepid_associations|17|CREATE UNIQUE INDEX originServer_originId on global_threepid_associations (originServer, originId)
How do I resolve this error? I can't see any issues with the schema.
Expression indexes were added in version 3.9.0.
Apparently, sysdent uses an older SQLite version.

How to return the last primary key after INSERT in pymysql (python3.5)?

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
for example, how to get the primary key id of the last record that I insert into the table by cursor.execute("insert into ...", ...)?
after inserting,You can get it as:
cursor.execute('select LAST_INSERT_ID()') or use cursor.lastrowid

Categories

Resources