Auto Incrementing Primary Key Using Entry Widgets into Table - python

I'm using entries to insert data points into a table where the 'ID' is auto-incrementing. I'm encountering an issue I had when I was working on importing a table with the id being based on auto incrementing, but the solutions I got for that haven't worked with this so far.
import tkinter as tk
import sqlite3
c.execute("""CREATE TABLE IF NOT EXISTS tbl (
id INTEGER PRIMARY KEY NOT NULL,
data text
)""")
def add_equipment():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO tbl VALUES(:ID + null, :data)
{"data":data_ent.get()
})
conn.commit()
conn.close()
Doing this gives me an error of did not supply value for binding parameter id, removing the ':id + null' gives me an error of 1 column doens't have a supplied value. I used a for loop on the import version of this, but when I tried to do a loop as:
for row in c.fetchall():
c.execute('variable for the insert command & data', row)
it gives me no error, but doesn't insert the data into the table. I assume the for loop is wrong, but I'm not sure what it should be since this is meant to insert a single record at a time.

def add_equipment():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO tbl VALUES(:ID + null, :data)
{"id":'NULL',
"data":data_ent.get()
})
conn.commit()
conn.close()
This gives id a binding parameter and allows the null to auto increment as supposed to.

Related

Python SQLite3, table not showing updates

I am trying to create a database with SQLite3 in Python.
Creating a table appears to work, but whenever I try to insert data, it doesn't seem to add anything to the database as fetchall() returns nothing, However, if I try to create the ID again, it complains about
unique constraint failed.
Initialization:
import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()
Table Creation:
c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY,
First TEXT NOT NULL,
Last TEXT NOT NULL,
Middle TEXT NOT NULL,
Gender TEXT NOT NULL);""")
conn.commit()
Data Insert:
c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()
Fetching Tables:
print(c.fetchall())
c.close()
conn.close()
When dropping the table into an online reader, it also appears empty.
EDIT:
This is what is shown in the db reader, and in google sheets,
large list of blanks / ";" then this
c.fetchall() would return all of the rows from a SELECT query, which you aren't doing.
import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()
c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);""")
conn.commit()
c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())
will happily print
[(6, 'First', 'Last', 'Hello', 'Male')]
As an aside, your code is vulnerable to SQL injection attacks, and you should do
import sqlite3
conn = sqlite3.connect("login.db")
c = conn.cursor()
c.execute(
"""CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);"""
)
conn.commit()
c.execute(
"INSERT INTO Login (ID, First, Last, Middle, Gender) VALUES (?,?,?,?,?)",
(6, "First", "Last", "Hello", "Male"),
)
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())

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

Inserting Pandas Dataframe into MySQL table using Autoincrement to automatically generate primary key

I've a Pandas dataframe which I'm trying to insert into a MySQL table, using MySQLdb and to_sql. The table has 'allocationid' as primary key and autoincrement.. I will want to do this daily, deleting out the day's previous data from the MySQL table and reinserting updated data from the Pandas dataframe. Hence would like the primary key to autoincrement automatically (I won't be using it down the line, but may want to refer to it).
code is...
columns = ('date','tradeid','accountid','amount')
splitInput = pd.DataFrame(columns = columns)
splitInput['accountid'] = newHFfile['acctID']
splitInput['tradeid'] = newHFfile['Ref']
splitInput['amount'] = newHFfile['AMOUNT1']
splitInput['date'] = newHFfile['Trade Date']
db = MySQLdb.connect(host="(hostIP)", port=3306, user="user", passwd="(passwd)", db="(database)")
cursor = db.cursor()
query = """delete from splittrades where date = """ + runymdformat + """ """
cursor.execute(query)
db.commit()
splitInput.to_sql(con = db, name = 'splittrades',if_exists = 'append',flavor = 'mysql',index = False)
db.commit()
db.close()
The problem is that without adding a column for primary key, I get 'OperationalError: (1364, "Field 'allocationid' doesn't have a default value")'
If I add a primary key column and leave it blank, null, I get OperationalError: (1366, "Incorrect integer value: '' for column 'allocationid' at row 1")
If I use 1 or 0 in the allocationid column I get a duplicated value error msg.
MySQL usually auto-increments the primary key if you don't specify it - is there a way I can make this work from Python?
PS am not a Python expert so pls treat me gently - thanks :-)

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