import sqlite3
conn = sqlite3.connect('serpin.db')
c = conn.cursor()
c.execute("""CREATE TABLE Gene(Gene_name TEXT, Organism TEXT, link_2_gene_with_ID TEXT, Number_SpliceForm INTEGER,ID_mRNA INTEGER, ID_Prt INTEGER);""")
c.execute(".import practice.csv Gene --csv")
c.execute(".mode column")
c.execute("select * from Gene;")
print(c.fetchall())
conn.commit()
conn.close
I can run all these commands individually on my own on the windows terminal in sqlite3. However I get multiple errors running this code, which is roughly what i used in a bash script where i got no errors. The first error I receive is an error that ssays "table Gene already exists." Now even if i comment out that line, i also get an error in the import command, where it says there is a syntax error with the period right before import. These are all sqlite3.OperationalError. I have tried running these commands on their own directly in sqlite3 and have no issues, so i'm not sure what the problem is.
I have no database in this folder, so I'm not sure how the table is already made.
edit(solution): the output of this is not formatted correctly, but this runs without errors.
import csv,sqlite3
conn = sqlite3.connect('serpin.db')
c = conn.cursor()
try:
c.execute("""CREATE TABLE Gene (Gene_name TEXT, Organism TEXT, link_2_gene_with_ID TEXT, Number_SpliceForm INTEGER,ID_mRNA INTEGER, ID_Prt INTEGER);""")
except:
pass
path = r'C:\Users\User\Desktop\sqlite\practice.csv'
with open(path,'r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['Gene_name'], i['Organism'],i['link_2_gene_with_ID'],i['Number_SpliceForm'],i['ID_mRNA'],i['ID_Prt'] ) for i in dr]
c.executemany("INSERT INTO Gene (Gene_name,Organism,link_2_gene_with_ID,Number_SpliceForm,ID_mRNA,ID_Prt) VALUES (?,?,?,?,?,?);", to_db)
c.execute("select * from Gene;")
print(c.fetchall())
conn.commit()
conn.close
About the fact that you may already have created the table and that gives you an error:
try:
c.execute("""CREATE TABLE Gene(Gene_name TEXT, Organism TEXT, link_2_gene_with_ID TEXT, Number_SpliceForm INTEGER,ID_mRNA INTEGER, ID_Prt INTEGER);""")
except:
pass
To import the file, I report here from another answer from the user mechanical_meat
Importing a CSV file into a sqlite3 database table using Python:
import csv, sqlite3
con = sqlite3.connect(":memory:") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here
with open('data.csv','r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['col1'], i['col2']) for i in dr]
cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()
Don't know about the .mode command, but as far as I know, operation in SQLite3 in python are all in capital letters, thus also select should be SELECT
The following codes give me an error when i try to submit info to sqlite data base created from function
def submit():
conn =
sqlite3.connect('addr.db')
c = conn.cursor()
c.execute("INSERT INTO addr.
VALUES( ............
.......
I set up the dictionary and end the function with
conn.commit()
conn.close()
Anytime i call the function using a tkinter button widget it shows the following error:
sqlite3.OperatioblError: no such table: addr
Please is ther something i need to do to allow my function create the database?
from tkinter import *
from tkinter import messagebox
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root',passwd='Alok1823!',database='kbc')
mycursor = mydb.cursor()
tempuser='tarran09'
mycursor.execute("insert into `kbc`.`player` ('username') values (tempuser) ")
How do I add values to a table from Python editor. The values are not direct values but rather stored in variables. I don't know what the contents of that variable are at any given moment. So how do add the value of these variables into one the tables of mySQL database?
If the variable is string then:
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root',passwd='Alok1823!',database='kbc')
mycursor = mydb.cursor()
tempuser='tarran09'
mycursor.execute(f"insert into kbc.player (username) values ('{tempuser}')")
mydb.commit()
If you are using python version < 3.6, then
mycursor.execute("insert into kbc.player (username) values ('{}')".format(tempuser))
Code is follow. How to get replaced ? by value of variables [table, url]?
Expected SQL command is select * from OTHER_URL where url="http://a.com/a.jpg"
This SQL command occurs no error on the sqlite3 command line interface.
import sqlite3
from contextlib import closing
dbname = "ng.db"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS OTHER_URL (url TEXT)")
conn.commit()
table = "OTHER_URL"
url = "http://a.com/a.jpg"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute('select * from ? where url="?"', [table, url])
print c.fetchone()
There are two errors here. Firstly, you can't use parameter substitution for table names (or column names), only for values. You need to use string interpolation for anything else.
Secondly, you don't need quotes around the value parameter; the substitution will take care of that.
So:
c.execute('select * from {} where url=?'.format(table), [url])
I write a python code to create a table,but when I open DB browser for SQLite, it does not the table I have created, I am new to database, so can anyone tell me what is wrong with it ? Many thanks!
import sqlite3
conn = sqlite3.connect('test1.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Test''')
cur.execute('''
CREATE TABLE Test (azaz TEXT, count INTEGER)''')
cur.execute('''INSERT INTO Test (azaz, count)
VALUES ( 'aa', 1 )''' )
conn.commit()
conn.close()
image link:imgur.com/epfar.png
Your code is right and if you try:
import sqlite3
conn = sqlite3.connect('test1.sqlite')
row = conn.execute('SELECT * FROM Test').fetchone()
print("azaz=", row[0])
print("count=", row[1])
You will see this output:
('azaz=', u'aa')
('count=', 1)
So the table has been created and values has been inserted in the table.
I have just tested your code and it works flawlessly. I have used python-3.5 and DB Broswer for sqlite, tested on window 7 pro.