I am trying to insert 6 values into separate columns in a database and when running my code i'm getting the near "From" syntax error can someone help?
def setup_transactions(db, filename):
'''(str, str) -> NoneType
Create and populate the Transactions table for database db using the
contents of the file named filename.'''
data_file = open(filename)
con = sqlite3.connect(db)
cur = con.cursor()
# create and populate the table here
cur.execute('CREATE TABLE Transactions(Date TEXT, Number TEXT, Type TEXT, From TEXT, To TEXT, Amount REAL)')
for line in data_file:
data = line.split()
cur.execute('INSERT INTO Accounts VALUES (?, ?, ?, ?, ?, ?)', (data[0], data[1], data[2], data[3], data[4], data[5]))
data_file.close()
cur.close()
con.commit()
con.close()
the error is this:
Traceback (most recent call last):
Python Shell, prompt 2, line 1
File "/Users/user1/Desktop/assignment 2/banking.py", line 64, in
cur.execute('CREATE TABLE Transactions(Date TEXT, Number TEXT, Type TEXT, From TEXT, To TEXT, Amount REAL)')
sqlite3.OperationalError: near "From": syntax error
cur.execute('CREATE TABLE Transactions(Date TEXT, Number TEXT, Type TEXT, From TEXT, To TEXT, Amount REAL)')
You have a column named From. From is a sql Keyword, I would avoid using it as it may cause syntax errors
Try something more descriptive like
cur.execute('CREATE TABLE Transactions(date_created TEXT, current_Number TEXT, record_type TEXT, from_somewhere TEXT, to_somewhere TEXT, amount REAL)')
Related
Why is my program giving me error indicating that that column does not exist in my Sqlite3 Tasks-table? Here is my code:
class Db:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
def create_table(self):
create_Tasks_table = '''CREATE TABLE Tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
deadline TEXT,
state INTEGER);'''
self.cursor.execute(create_Tasks_table)
self.conn.commit()
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = """INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?), (title, notes, deadline, state)"""
self.cursor.execute(add_to_Tasks_table)
self.conn.commit()
if __name__ == "__main__":
db = Db()
db.create_table()
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
I checked with DB Browser for SQlite that table is created correctly and column name is correct, as indicated on this picture:
EDIT: Here is full error:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\project\mytest.py", line 91, in <module>
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
File "C:\Users\User\PycharmProjects\project\mytest.py", line 36, in add_task
self.cursor.execute(add_to_Tasks_table)
sqlite3.OperationalError: no such column: title
The problem with your code is that you included the tuple that contains the parameters that you pass inside the sql statement.
It should be placed as the 2nd argument of cursor.execute():
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = "INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?)"
self.cursor.execute(add_to_Tasks_table, (title, notes, deadline, state))
self.conn.commit()
I have 2 things I needed help with:
1) I am unsure as to how I can check if a table exists in python using the sqlite3 library.
2) I am unsure as to how I can save variables from the program to a database. I want to be able to check if UserDetails exists before making the database.
I've been reading around and everyone is doing stuff differently,
Here is the section of my code that is responsible for saving the variables:
connection = sqlite3.connect("UserDetails.db")
crsr = connection.cursor()
#create table
sql_command = table_creator
crsr.execute(sql_command)
#insert values into table
data_to_insert = (username, first_name, surname, age, user_salt, password_hash, date_today)
sql_command = """INSERT INTO UserDetails VALUES ((?, ?, ?, ?, ?, ?, ?), data_to_insert);"""
crsr.execute(sql_command)
connection.commit() #save changes
connection.close() #terminate connection
and in case you want to see table_creator it looks like this:
table_creator = '''CREATE TABLE `UserDetails` (
`Username` VARCHAR(8) NOT NULL,
`Firstname` VARCHAR(10) NOT NULL,
`Surname` VARCHAR(20) NOT NULL,
`Age` INT(2) NOT NULL,
`Salt` VARCHAR(10) NOT NULL,
`Hash` VARCHAR(64) NOT NULL,
`Date` DATE NOT NULL,
PRIMARY KEY (`UserName`)
);'''
I will appreciate and feedback or support.
I am still learning to code, and my CompSci teacher doesnt teach us Python specifically, so what I know is self taught.
Oh and this is the error message I get:
Traceback (most recent call)
File "c:/Users/Arslan/Project A2/login.py", line 99, in <module>
save_details()
File "c:/Users/Arslan/Project A2/login.py", line 93, in save_details
crsr.execute(sql_command)
sqlite3.OperationalError: no such column: data_to_insert
How to check if a table exists or no :
The first way :
Use this query:
SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
Modify {table_name} with your table to check
There are two cases :
. If the cursor equal to 0 ==> the table does not exist
Else, the table exists
The second way:
Use :
PRAGMA table_info(table_name)
example:
The third way :
Use this query :
select 1 from table
It will return the constant 1 for every row of the table if the table exists, or nothing if not.
There are many other ways, but I listed the best in my opinion.
How to save variables from the program to a database:
To insert data into sqlite3, you can use :
cursor.execute("insert into UserDetails values (?, ?, ?, ?, ?, ?, ?)", (username, firstname, surname, age, salt, hash, date))
DON'T USE (SQL injection):
cursor.execute("insert into UserDetails values ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')".format(username, firstname, surname, age, salt, hash, date))
Don't forget :
conn.commit()
Or you can use instead of it the connection as a context manager:
with conn:
# then cursor.execute..
1) I am unsure as to how I can check if a table exists in python using the sqlite3 library.
Use CREATE TABLE IF NOT EXISTS:
table_creator = '''CREATE TABLE IF NOT EXISTS `UserDetails` (
`Username` VARCHAR(8) NOT NULL,
`Firstname` VARCHAR(10) NOT NULL,
...
);'''
2) I am unsure as to how I can save variables from the program to a database.
You can pass variables for insert with the following syntax:
data_to_insert = (username, first_name, surname, age, user_salt, password_hash, date_today)
sql_command = '''INSERT INTO UserDetails VALUES (?, ?, ?, ?, ?, ?, ?)''';
crsr.execute(sql_command, data_to_insert )
As you can see I am trying to fetch data from this API-endpoint https://api.coindesk.com/v1/bpi/currentprice.json and I have chosen few data I want to fetch and store it in SQLite.
When I try to save it in a database it gives me this error:
Traceback (most recent call last):
File "bitcoin.py", line 41, in <module>
cur.execute("INSERT INTO COINS (Identifier, symbol, description) VALUES (?, ?, ?);", to_db)
sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a dictionary (which has only names).
How can I store the some of the data from API-endpoint into the database?
I'm doing this to learn programming and still new to this so hopefully, you can guide me in the right way.
Here is what I have tried so far:
import requests
import sqlite3
con = sqlite3.connect("COINS.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS COINS')
cur.execute(
"CREATE TABLE COINS (Identifier INTEGER PRIMARY KEY, symbol TEXT, description TEXT);"
)
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
to_db = r.json() # I do not have to do it in json, CSV would also be another
# solution but the data that is been stored cannot be static.
# It has to automatically fetch the data from API-endpoint
cur.execute("INSERT INTO COINS (Identifier, symbol, description) VALUES (?, ?, ?);", to_db)
con.commit()
con.close()
import requests
import sqlite3
con = sqlite3.connect("COINS.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS COINS')
cur.execute(
"CREATE TABLE COINS (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENTUNIQUE,
symbol TEXT, description TEXT);")
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
to_db = r.json()
des=to_db['bpi']['USD']['description']
code=to_db['bpi']['USD']['code']
cur.execute("INSERT INTO COINS (symbol, description) VALUES (?, ?);",
(des,code))
con.commit()
con.close()
Check full code
I am getting an error message stating
ValueError: operation parameter must be str
while inserting data into the table
here is my code below
import csv
import sqlite3
conn = sqlite3.connect('results.db')
curs = conn.cursor()
total = []
headerlist = []
headerlisttype = []
rowindex = 1
def parse_csv():
'''
Adds all the rows in csv file to total list
'''
with open('3-1 RESULTS.csv', 'r') as csvfile:
parser = csv.reader(csvfile)
headerlist = next(parser)
for row in parser:
total.append(row)
# end parse_csv
def create_table():
'''
Creates a table with just auto incremented SNO column
'''
sql = '''CREATE TABLE IF NOT EXISTS RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) '''
curs.execute(sql)
conn.commit()
#end create_table function
def insert_to_table(row):
global rowindex
sno = rowindex
rowindex += 1
reg, name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, sgpa, cgpa = row
sql = '''INSERT INTO RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''',
(int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))
try:
curs.execute(sql)
except Exception as e:
print(e)
def print_from_table():
sql = ''' SELECT * FROM RESULTS31 '''
curs.execute(sql)
data = curs.fetchall()
for row in data:
print(row)
parse_csv()
create_table()
for row in total:
insert_to_table(row)
print_from_table()
can anyone please find the error in my code
Help will be much apreciated
INSERT wants only the column names, not any column types.
And execute() has two parameters, the SQL statement text, and the list of SQL parameters:
sql = '''INSERT INTO RESULTS31 (SNO, REGNUMBER, ...'''
params = (int(sno), ...)
curs.execute(sql, params)
I've never seen this Python construct:
sql = '''INSERT INTO RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''',
(int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))
Unless this is perfectly valid syntax for formatting strings, your code will create a tuple and bind it to 'sql'
look into format()
I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance!
from sqlite3 import *
import feedparser
data = feedparser.parse("some url")
conn = connect('location.db')
curs = conn.cursor()
curs.execute('''create table location_tr
(id integer primary key, title text ,
updated text)''')
for i in range(len(data['entries'])):
curs.execute("insert into location_tr values\
(NULL, data.entries[i].title,data.feed.updated)")
conn.commit()
curs.execute("select * from location_tr")
for row in curs:
print row
And Error is:
Traceback (most recent call last):
File "F:\JavaWorkspace\Test\src\sqlite_example.py", line 16, in <module>
(NULL, data.entries[i].title,data.feed.updated)")
sqlite3.OperationalError: near "[i]": syntax error
Try
curs.execute("insert into location_tr values\
(NULL, '%s', '%s')" % (data.entries[i].title, data.feed.updated))
the error should be this line
curs.execute("insert into location_tr values\
(NULL, data.entries[i].title,data.feed.updated)")
data.entries[i].title comes from Python. So if you enclose it in double quotes, it becomes a literal string, not a value. It should be something like this:
curs.execute("insert into location_tr values (NULL," + data.entries[i].title +","+data.feed.updated+")")