How to add auto increment id with character for python sqlite - python

import sqlite3
conn = sqlite3.connect('carlist.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS carlist(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Brand text NOT NULL,
Model text NOT NULL,
License Plate text NOT NULL,
Year INTEGER)""")
I'm trying to make auto increment ID with the character when I add the new data
Example for ID : AFK000001, AFK000002, AFK000003 and etc. This should be auto field.

If you are using SQLite 3.31.0+ you can define a generated column:
aID TEXT GENERATED ALWAYS AS ('AFK' || SUBSTR('000000' || ID, -6))
This column as it is defined will not be stored in the table, but will be generated every time you query the table.
If you want it to be stored then you can add the keyword STORED at the end of its definition.

The AUTO_INCREMENT is exclusive for integers and there is no way to do that automatically, however you can make a little script to achieve that by :
Store last ID
Get the integer subString
Increment its value and add it to the character subString
Store it in table

Related

Composite Primary Key and autoincremented ID

I am trying to build a composite primary key for my tabels. They should also have a self incremented id. My problem is that when I use a composite primary key the ID becomes NULL (as seen in the pictures)
here it works as it should but no composite key
here the id is NULL no matter what.
I tried different synatxes and also key words like NOT NULL and AUTOINCREMENT but nothing seems to work.
Here is the code without composite key
mystr = "CREATE TABLE IF NOT EXISTS KM%s(id INTEGER PRIMARY KEY, date TEXT, client INTEGER)"%(month.replace('-',"))
print(mystr)
c.execute(mystr) #create a table
conn.commit()'''
Here is the code with COMPOSITE KEY
mystr = "CREATE TABLE IF NOT EXISTS KM%s(id INTEGER, date TEXT, client INTEGER, primary key (id, client)"%(month.replace('-',"))
print(mystr)
c.execute(mystr) #create a table
conn.commit()
I was sure that I'd used autoincremented integer columns in the past which were not primary keys, but it certainly doesn't work today with SQLite.
I must echo what #forpas has already said in the comment that you just can't do that.
The solution would be to add the UNIQUE constraint to id and generate your ID programmatically as you go. You do not need to track your current maximum ID because you can simply ask SQLite what the max is:
SELECT MAX(id) FROM KM<month>;
Increment that value by 1 and include it in your INSERT INTO statement.
I'd like to offer a couple of tips:
Using two integers as your composite key is a bad idea. Take composite key 1315 for example. Is that client 315 with an ID of 1, client 15 with an ID of 13, or client 5 with an ID of 131? It's true that primary keys are just for searching and do not have to be unique in many cases, but using integers generally does not work well.
The second tip is not to create a new database table for each month. A very good rule is that identically-structured tables should be combined into a single table. In this case you would add a column called month (actually, it would be 'date' then you would search by month) and keep everything in one table, not one table per month.

My Flask app returns an unexpected syntax error

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.

MySQL would not create a table if I change the name of a column

I am using a python code to create MySQL tables.
I am fine to create table using a specific name for my columns, but as soon as I want to change them, the tables are not created anymore.
This code bellow works without any problems
DROP TABLE IF EXISTS sector_tb;
CREATE TABLE sector_tb (
id INT NOT NULL AUTO_INCREMENT,
sector VARCHAR(255) NOT NULL DEFAULT '',
district_id INT NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX sector (sector)
)
COLLATE='latin1_swedish_ci'
;
As soon as I decide to change the name of 'sector' to 'sector1' or anything else, MySQL does not create the table anymore. The code below does not create the table anymore.
CREATE TABLE sector_tb (
id INT NOT NULL AUTO_INCREMENT,
sector1 VARCHAR(255) NOT NULL DEFAULT '',
district_id INT NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX sector (sector)
)
COLLATE='latin1_swedish_ci'
;
There are no errors shown while running the code.
There is an obvious error in second statement:
column name in the index doesn't match column name in the table.
sector1 VARCHAR(255)
UNIQUE INDEX sector (sector)
If your Python code does not report any errors, you must improve error handling.
Two options - drop the original sector_tb and run your second script or rename your column using the alter table command.

How to fix syntax error in SQLite in Python

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)

Populate a SQL table column based on other values in table

I have table that is already populated with the tweets. I am reading some dictionaries from the tweet using json. I am using SQLite3 in Python.
TwTbl = """Create table TwTbl
(created_at text, id text, geo_count integer, user_id integer, text text, geo_id integer, source text,in_reply_to_user_id integer, retweet_count integer,
constraint fk_UserEntry
foreign key (user_id) references UserEntry(id)
constraint fk_Geo
foreign key (geo_count) references Geo(Id)
);"""
c.execute(TwTbl)
Now I have to add a column to this table "LenTweet" which is supposed to contain the length of coloumn "Text". I can add the coloumn using
c.execute("ALTER TABLE TwTbl ADD LenTweet text").fetchall()
But, I do not know how to populate this newly created coloumn with the length of "Text" column. All I can think of is to recreate the table and insert the length right there, while reading the tweets. The coloumn has to be populated based on the values that are in the table currently. This does not get triggered with any inserts. Can someone please tell me a way, so I can populate the table with the data that I have already in it?
Thanks in advance.
UPDATE TwTbl
SET LenTweet = length(text)
Where text is the name of the column that you want to know the length of. See this page for details on the length function.
Also, LenTweet should probably be numeric rather than a text field.

Categories

Resources