Python sqlite how to alter table add columb if not exists - python

I want: if column not exists, add column
def tablo_olustur():
cursor.execute("CREATE TABLE IF NOT EXISTS "+asin+"(Tarih TEXT)")
con.commit()
tablo_olustur()
def veri_ekle(Satıcı_ismi,Stok_Miktarı):
cursor.execute("INSERT INTO "+asin+' (Tarih, "{}") values (?,?)'.format(Satıcı_ismi),(currentDT,Stok_Miktarı))
con.commit()
#def ver_ekle2(Stok_Miktarı):
# cursor.execute("INSERT INTO "+asin+" (Satıcı_ismi, '{}') values (?,?)".format(currentDT),(Satıcı_ismi,Stok_Miktarı))
# con.commit()
def sutun_ekle(sutun):
cursor.execute("ALTER TABLE "+asin+' ADD COLUMN "{}" '.format(sutun))
con.commit()
I get sqlite3.OperationalError: duplicate column name: xxxx error from python

You can try this, if column exists it will add if not you can check if any column of same name already exists in the table
def sutun_ekle(sutun):
try:
cursor.execute("ALTER TABLE "+asin+' ADD COLUMN "{}" '.format(sutun))
con.commit()
except:
cursor.execute("PRAGMA table_info(asin)")
print cursor.fetchall() #prints the list of existing column header

You need to inspect your table to see whether the column exists:
# replace your_table with your table you want to inspect
existing_cols = [row.column_name for row in cursor.columns(table='your_table')
# check if the column you want to add is in the list
if col_add in existing_cols:
pass # do nothing
else:
# alter table
# replace your_table with the table you want to alter
# replace varchar(32) with the data type for the column
cursor.execute("ALTER TABLE your_table ADD COLUMN {} varchar(32)".format(col_add)
con.commit()

Related

Create multiple table with python in Sqlite

I've search trought a lot a internet site and I cannot find the answer.
I try to create 4 tables in my SQLite database with this code:
try:
conn = sqlite3.connect(os.path.join(current_directory, 'fidouda.db'))
c = conn.cursor()
c.execute('''CREATE TABLE Clients (ID INTEGER PRIMARY KEY AUTOINCREMENT, Prenom, Nom, Adresse, Email, Telephone, Genre, Factures, Fidelite);''')
c.execute('''CREATE TABLE Factures (ID, Client, Items, Date, Prix, Promotion, Sous-total, Total, Payer, Rpayer);''')
c.execute('''CREATE TABLE Inventaire (Stock, Nom, Prix);''')
c.execute('''CREATE TABLE Rabais (Nom, Pourcentage);''')
except Error as e:
print(e)
finally:
if conn:
conn.close()
return os.path.join(current_directory, fname)
The problem is that only the first table are created. How can I create all my table ?
If you run this code, it will output this error:
sqlite3.OperationalError: near "-": syntax error
Specifically, the hyphen in the column Sous-total, you can either surround the column name in quotes, like this:
c.execute('''CREATE TABLE Factures (ID, Client, Items, Date, Prix, Promotion, 'Sous-total', Total, Payer, Rpayer);''')
Or pick another column name that won't cause problems.

Creating database in Python using sqlite3

I got stuck when I was trying to create database in Python using sqlite3. The below is what I did. When I tried to run, it kept telling me the tables already exist. I couldn't figure out why. Thanks!
import sqlite3
variables = (data)
functions = (data)
var_func = (data)
conn = sqlite3.connect('python_database')
c = conn.cursor()
#create table
c.execute(''' CREATE table variable_table (
id integer,
name text,
module text,
type text,
desc text) ''')
c.execute(''' CREATE table function_table (
id integer,
name text) ''')
c.execute(''' CREATE table var_func_table (
variable_id integer,
function_id integer,
type text) ''')
#fill tables with data
for row in variables:
c.execute ('insert into variable_table values (?,?,?,?,?)', row )
for row in functions:
c.execute ('insert into function_table values (?,?)', row)
for row in var_func:
c.execute ('insert into var_func_table values (?,?,?)', row)
# Save (commit) the change
conn.commit
conn.close

Update Table with a valuable ( Sqlite)

i can't insert or update with a valuable.
i don't know syntax
self.Value = self.Pass.text()
Database.ram.execute('''INSERT INTO Pass VALUE (?)''',self.Value)
thanks
There is not much of your code to go on but I would use the following SQLite statement:
Database.ram.execute('UPDATE table SET column = ?', (self.Value))
conn.commit() # with conn = sqlite3.connect('db name')
And if you want to insert:
Database.ram.execute('INSERT INTO table (column) VALUES(?)', (self.Value))
conn.commit() # with conn = sqlite3.connect('db name')

SQLite: INSERT or REPLACE w/ null PRIMARY KEY

I am trying to INSERT or REPLACE INTO t1 if the name is already there. I understand if the id is set then replace will work, but I need it to react to name.
import sqlite3
def insert(name):
cur.execute('INSERT OR REPLACE INTO t1(name) VALUES(?)', [name])
def select():
return cur.execute('SELECT * FROM t1').fetchall()
conn = sqlite3.connect('test')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS t1')
cur.execute('''CREATE TABLE IF NOT EXISTS t1(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)''')
insert('jack')
insert('jack')
insert('jack')
print select()
output
[(1, u'jack'), (2, u'jack'), (3, u'jack')]
INSERT or REPLACE ... will do replace only if there are collisions. And as your name column isnt collidable, this event cannot accur (at least not on name). You need to make name collidable:
CREATE UNIQUE INDEX IF NOT EXISTS iname ON t1 (name)
Also note that you dont need to have id column, because sqlite3 has ROWID on every table.

MYSQL and python error

I want to insert data in MYSQL database using python
here my code
import MySQLdb
#connect to db
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
#setup cursor
cursor = db.cursor()
#create anooog1 table
cursor.execute("DROP TABLE IF EXISTS try")
sql = """CREATE TABLE try (
COL1 INT, COL2 INT )"""
cursor.execute(sql)
#insert to table
cursor.execute("""INSERT INTO try VALUES (%s,%s)""",(188,90))
db.commit()
db.rollback()
#show table
cursor.execute("""SELECT * FROM try""")
print cursor.fetchall()
db.close()
but the error is in my sql
Error: `new_schema`.`try`: table data is not editable because there is no primary key defined for the table ...
What shall I do?
Your error is because you've created a table with no primary key.
Use this statement (or similar):
sql = """CREATE TABLE try (COL1 INT, COL2 INT, PRIMARY KEY (COL1))"""
Here we specify that COL1 is to be the primary key for the table. Modify as you need to suit your requirements.
If you wanted to add a string column (with length 128) to your table:
CREATE TABLE try (COL1 INT, COL2 INT, MyString VARCHAR(128), PRIMARY KEY (COL1))

Categories

Resources