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
Related
i'm a bit of an amateur IT Professional who has been getting to grips with Python and Django. This query is just for Python and SQLite3.
So I have the following code, which is meant to take an input from the user, and then pass it to a function I have created.
from dbadd import inputdetails
import sqlite3
conn = sqlite3.connect('torndata.db')
c = conn.cursor()
print('Enter Name')
u_name = str(input())
print('Enter Age')
u_age = int(input())
print('Enter Gender')
u_gender = str(input())
inputdetails(u_name, u_age, u_gender)
conn.close()
And this is the function it is calling:
import sqlite3
conn = sqlite3 . connect ( 'torndata.db' )
cursor = conn.cursor ()
def inputdetails(u_name,u_age,u_gender):
cursor.execute("""
INSERT INTO userdata(name, age, gender)
VALUES (?,?,?)
""", (u_name, u_age, u_gender))
conn.commit()
I get no errors when it runs, but when I run the following, it shows no data has been moved to the table I have specified.
c.execute("SELECT * FROM userdata")
print(c.fetchall())
conn.commit()
conn.close()
The database is already created within SQLite3 and the table has been set up, I can query it directly.
Bad indent. The commit statement is not part of the function.
With the next cmds I am trying to upload a csv file where columns are separated by tabs and sometimes null values can be assigned to a column.
conn = psycopg2.connect(host="localhost",
port="5432",
user="postgres",
password="somepwd",
database="mydb",
options="-c search_path=dbo")
...
cur = conn.cursor()
with open(opath, "r") as opath_file:
next(opath_file) # skip the header row
cur.copy_from(opath_file, table_name[3:], null='', columns=cols.split(','))
cols has a string with the column names separated by ','
the table with name table_name[3:] belongs to the dbo schema
This code runs, no error is reported but no data is uploaded. The owner of the db is postgres.
Any ideas?
Would you believe me if the problem was I needed to run
conn.commit()
after the cur.copy_from cmd?
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 want to insert data from a CSV file into a PostgreSQL table. The table
structure is given below. But I am unable to give input of INTEGER type values.
It is showing error like-
DataError: invalid input syntax for integer: "vendor_phone"
LINE 1: ...vendor_phone,vendor_address)VALUES ('vendor_name','vendor_ph...
It is working fine if I use VARCHAR type. But i need to use integer values.
CREATE TABLE vendors (
vendor_id SERIAL PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
vendor_phone INTEGER,
vendor_address VARCHAR(255) NOT NULL
)
import psycopg2
import csv
database = psycopg2.connect (database = "supplier", user="postgres", password="1234", host="localhost", port="5432")
cursor = database.cursor()
vendor_data = csv.reader(open('vendors.csv'),delimiter=',')
for row in vendor_data:
cursor.execute("INSERT INTO vendors (vendor_name,vendor_phone,vendor_address)"\
"VALUES (%s,%s,%s)",
row)
print("CSV data imported")
cursor.close()
database.commit()
database.close()
instead of cursor, you can use below statement to load data directly from CSV to table which skips Header of the CSV file
COPY vendors (vendor_name,vendor_phone,vendor_address) FROM 'vendors.csv' CSV HEADER;
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.