Populate a SQL table column based on other values in table - python

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.

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.

PYTHON ERROR OperationalError: near "ident": syntax error when i try to introduce UNIQUE constraint

I am trying to name some columns as unique in my SQLite table, but I get an error for the next column field when I do. In this table, it's the ident column. can someone tell me why?enter image description here when I try to execute the table, it does not work. If I try this without the UNIQUE constraint, it works. But I need the unique control to avoid duplicates in the table.
enter image description here
run_table = '''CREATE TABLE IF NOT EXISTS runways( id INTEGER UNIQUE, airport_ref INTEGER, airport_ident TEXT); #create table into database c.execute(run_table)

How to add auto increment id with character for python sqlite

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

sqlite3 prints without explicit command

I'm trying to get a rowid if a data row exists. What I have now is
row_id = self.dbc.cursor.execute("SELECT ROWID FROM Names where unq_id=?",(namesrow['unq_id'],)).fetchall()[0][0]
where namesrow is a dictionary of column names with corresponding data to fill into the table. The problem is this prints 'unq_id' when runs and I'm not sure how to get rid of it.
I'm using sqlite3 and python. Any help's appreciated!
quoting the sqlite documentation:
With one exception noted below, if a rowid table has a primary key
that consists of a single column and the declared type of that column
is "INTEGER" in any mixture of upper and lower case, then the column
becomes an alias for the rowid.
So if your unq_id is the integer primary key in this table, then rowid and unq_id will be the same field.

Stop values from being entered into database python sqlite

How would I stop sqlite3 from adding the same exact values into a table if it is the exact same but otherwise add it? I'm totaly new to sqlite and don't know how to do this.
When you create the table, specify a unique constraint:
create table foo ( name varchar, id integer, unique ( name, id) );
You should define your table as #Robᵩ answered.
If you don't want, however, change an existing table definition - in SQLite you are very limited in ALTER TABLE, you can create a unique index:
CREATE UNIQUE INDEX foo_idx ON foo (name, id);
Note you are not allowed to create this index until you remove all duplicates.

Categories

Resources