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
Related
i get TypeError: function takes exactly 2 arguments (3 given),
when i convert show_id and genre into list of tuples, i get ValueError: paramenter are of unsupported type.
import sqlite3
import csv
# create database
conn = sqlite3.connect("favorites8.db")
open("favorites8.db", "w")
db = conn.cursor()
# create table
db.execute("CREATE TABLE shows (id INTEGER AUTO INCREMENT, title TEXT NOT NULL, PRIMARY KEY (id))")
db.execute("CREATE TABLE genres (shows_id INTEGER, genre TEXT NOT NULL, FOREIGN KEY (shows_id) REFERENCES shows(id))")
# open csv file
with open("favorites.csv", "r") as file:
# create dictreader
reader = csv.DictReader(file)
# iterate over csv file
for row in reader:
# canonicalize title
title = row["title"].strip().upper()
# insert title
stmnt1 = "INSERT INTO shows (title) VALUES(?)"
show_id = db.execute(stmnt1, (title,))
# Insert genres
for genre in row["genres"].split(", "):
stmnt2 = "INSERT INTO genres (shows_id, genre) VALUES(?, ?)"
db.executemany(stmnt2, show_id, genre)
# commit changes
conn.commit()
conn.close()
# end with
I've fixed some mistakes and cleaned this up a bit:
conn = sqlite3.connect("favorites8.db")
db = conn.cursor()
db.execute("CREATE TABLE shows (id INTEGER NOT NULL PRIMARY KEY, title TEXT NOT NULL)")
db.execute("CREATE TABLE genres (shows_id INTEGER, genre TEXT NOT NULL, FOREIGN KEY (shows_id) REFERENCES shows(id))")
with open("favorites.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
title = row["title"].strip().upper()
stmnt1 = "INSERT INTO shows (title) VALUES(?)"
db.execute(stmnt1, (title,))
show_id = db.lastrowid
# Insert genres
data = []
stmnt2 = "INSERT INTO genres (shows_id, genre) VALUES(?, ?)"
for genre in row["genres"].split(", "):
data.append((show_id, genre))
db.executemany(stmnt2, data)
# commit changes
conn.commit()
conn.close()
There were a bunch of issues:
executemany accepts iterable as a second argument.
First execute statement does not return id, but cursor object, you need to retrieve it manually.
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.
I created an sqlite3 database using python to store data as shown in the code below
import sqlite3
conn = sqlite3.connect('tweets_data.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS tweets')
cur.execute('''
CREATE TABLE tweets (
id INTEGER PRIMARY KEY, created_at TEXT, full_text TEXT,
favourite_count INTEGER, retweet_count INTEGER)
''')
With this table, i want to store data from a JSON file (parts of the code are screenshotted and attached as images), which i have loaded as seen below
import json
with open('tweets.json') as f:
data = json.load(f)
After that, i tried inserting the data into the table using a for loop to pull out all unique tweet id and its following information. The code below is what i tried doing
for records in data:
cur.execute('INSERT INTO tweets (id, created_at, full_text, favourite_count, retweet_count) VALUES (?, ?, ?, ?, ?)',
(records['id'], records['created_at'], records['full_text'], records['user']['favourites_count'], records['retweet_count']))
conn.commit()
print(cur.fetchall())
conn.close()
However when i did a print (cur.fetchall()), the output was only an empty list. Nothing was inserted into the table. Thank you if anybody is able to help!
json file page 1
json file page 2
cur.fetchall() returns the result of the last query, and INSERT yields no result. You need a SELECT-query first:
cur.execute('SELECT * FROM tweets')
rows = cut.fetchall()
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())
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))