I have a database, and I wish to add multiple values to the same row. I am somewhat new with sqlite and databases, but I am learning. I know I can do this:
conn = sqlite3.connect('sqlitedb.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS threadTable(threadName varchar(30)')
c.execute('INSERT INTO threadTable (threadName) Values(?), x.Name')
This works for me, but I want to pass Multiple variables into the table, like so:
conn = sqlite3.connect('sqlitedb.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS threadTable(threadName varchar(30),threadKey varchar(10),threadID varchar(1000))')
c.execute('INSERT INTO threadTable (threadName),(threadKey),(threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))
When I try this, I get this error:
Traceback (most recent call last):
File "Files/main.py", line 39, in <module>
c.execute('INSERT INTO threadTable (threadName),(threadKey),(threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))
sqlite3.OperationalError: near ",": syntax error
you don't need parantheses around each column :
c.execute('INSERT INTO threadTable (threadName,threadKey,threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))
Related
I have a list that has two phone numbers and I'd like to put each phone number into its own column in an Access database. The column names are Phone_Number1 and Phone_Number2. How do I pass that to the INSERT statement?
phone_numbers = ['###.218.####', '###.746.####']
driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
filepath = 'C:/Users/Notebook/Documents/master.accdb'
myDataSources = pyodbc.dataSources()
access_driver = myDataSources['MS Access Database']
conn = pyodbc.connect(driver=driver, dbq=filepath)
cursor = conn.cursor()
phone_number_count = 1
for phone_number in phone_numbers:
column_name = "Phone_Number" + str(phone_number_count)
cursor.execute("INSERT INTO Business_Cards (column_name) VALUES (?)", (phone_number))
conn.commit()
print("Your database has been updated.")
This is what I have so far.
Traceback (most recent call last):
File "C:/Users/Notebook/PycharmProjects/Jarvis/BusinessCard.py", line 55, in <module>
database_entry(phone_numbers, emails, name, title)
File "C:/Users/Notebook/PycharmProjects/Jarvis/BusinessCard.py", line 47, in database_entry
cursor.execute("INSERT INTO Business_Cards (column_name) VALUES (?)", (phone_number))
pyodbc.Error: ('HYS22', "[HYS22] [Microsoft][ODBC Microsoft Access Driver] The INSERT INTO statement contains the following unknown field name: 'column_name'. Make sure you have typed the name correctly, and try the operation again. (-1507) (SQLExecDirectW)")
If you want to insert both numbers in the same row, remove the for loop and adjust the INSERT to consider the two columns:
phone_numbers = ['###.218.####', '###.746.####']
# ...
column_names = [f"PhoneNumber{i}" for i in range(1, len(phone_numbers) + 1)]
placeholders = ['?'] * len(phone_numbers)
cursor.execute(f"INSERT INTO Business_Cards ({', '.join(column_names)}) VALUES ({', '.join(placeholders)})", tuple(phone_numbers))
conn.commit()
# ...
I have made this python method:
def move_player_list_item(start_position,end_position,player_list_item):
conn = create_connection()
query = "DELETE FROM `player_list` WHERE `position`=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),))
conn.commit()
if start_position<end_position:
query = "UPDATE `player_list` SET `position`=`position`-1 WHERE `position`>? AND `position`<=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),str(end_position)))
conn.commit()
elif end_position<start_position:
query = "UPDATE `player_list` SET `position`=`position`+1 WHERE `position`>=? AND `position`<?;"
cur = conn.cursor()
cur.execute(query,(str(end_position),str(start_position)))
conn.commit()
query = query = "INSERT INTO `player_list` (`play`, `relative_type`, `relative_number`, `repeats`, `duration_milliseconds`, `duration_human`,`position`) VALUES (?,?,?,?,?,?,?)"
cur = conn.cursor()
cur.execute(query,(str(player_list_item["play"]),str(player_list_item["relative_type"]),str(player_list_item["relative_number"]),str(int(player_list_item["repeats"])),str(int(player_list_item["duration_milliseconds"])),str(player_list_item["duration_human"]),str(end_position)))
conn.commit()
return 1
When start_position<end_position works with no error.
But when end_position<start_position there is an error:
Traceback (most recent call last):
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 977, in <module>
main()
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 925, in main
sqlite3_functions.move_player_list_item(30,20,player_list_items_db[29])
File "C:/Users/Χρήστος Παππάς/Έγγραφα/projects/Papinhio player/Αρχεία βάσης δεδομένων (Sqlite3)/../Αρχεία πηγαίου κώδικα εφαρμογής (Python)/Αρχεία κώδικα python (Python files)/Συναρτήσεις sqlite3 (Sqlite3 functions).py", line 1125, in move_player_list_item
cur.execute(query,(str(end_position),str(start_position)))
sqlite3.IntegrityError: UNIQUE constraint failed: player_list.position
The only solution i have thought about is to remove the unique constraint.
Is there any better solution?
I'm trying to put some info into the database
import sqlite3
conn = sqlite3.connect("tutorial.db")
c=conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS stuffPlot(unix REAL,datestamp Text,keyword TEXT,value REAL)")
def data_entry(x,y,z,w):
c.execute("INSERT INTO stuffPlot VALUES({},{},{},{})".format(x,y,z,w))
conn.commit()
c.close()
conn.close()
x=int(input("enter a number"))
y=str(input("enter a str"))
z=int(input("enter a number"))
w=str(input("enter a str"))
create_table()
data_entry(x,y,w,z)
I want to write to the database, but it creates the following database
error:
data_entry(x,y,w,z)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in data_entry
sqlite3.OperationalError: no such column: name
Your strings are missing quotes so they're treated as column names, try this:
c.execute("INSERT INTO stuffPlot VALUES({},'{}','{}',{})".format(x,y,z,w))
Edit
Instead of the line above (which is vulnerable to SQL Injection) you should do it like this:
c.execute("INSERT INTO stuffPlot VALUES(?,?,?,?)", (x,y,z,w))
Hey your last line is calling this:
data_entry(x,y,w,z)
Its x,y,w,z, but in your function definition you are receiving this:
def data_entry(x,y,z,w): #sequence is x,y,z,w
So that created a bit confusion on what variable is what.
And also your strings will need to be enclosed inside single quotes as #scope mentioned.
So here's a working code
import sqlite3
conn = sqlite3.connect("tutorial.db")
c=conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS stuffPlot(unix REAL,datestamp Text,keyword TEXT,value REAL)")
def data_entry(x,y,z,w):
c.execute("INSERT INTO stuffPlot VALUES({},'{}',{},'{}');".format(x,y,z,w))
#fixed the quotes above
conn.commit()
c.close()
conn.close()
x=int(input("enter a number"))
y=str(input("enter a str"))
z=int(input("enter a number"))
w=str(input("enter a str"))
create_table()
data_entry(x,y,z,w) #fixed x,y,w,z to x,y,z,w
If you have any doubt please comment.
I am new to coding and databases, I can not get the query to work if I write it long hand but I have a lot to carry out and want it in a function but cannot get it to work, it returns a parameters error
import mysql.connector
def connection_check_1(query, value):
mydb = mysql.connector.connect(
host="******",
user="*****",
passwd="*****",
database="****"
)
mycursor = mydb.cursor()
mycursor.execute(query, (value))
myresult = mycursor.fetchall()
mydb.close()
return myresult
value = "sheep"
query = 'select inlicence from licence where animal = %s'
myresult = connection_check_1(query, value)
print(myresult)
Here is the SQL table I have
create table licence
(
animal varchar (20) primary key,
inlicence int (1)
);
This is the error I get
Traceback (most recent call last):
File "*******************", line 20, in
myresult = connection_check_1(query, value)
File "********************", line 13, in connection_check_1
mycursor.execute(query, (value))
File "********************************************88", line 246, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/home/kev/PycharmProjects/test bed/venv/lib/python3.5/site-packages/mysql/connector/connection_cext.py", line 535, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
I have tried changing the way the query is written, changing it to fetchall().
Wrapping a value with () doesn't turn it in to a tuple. You probably meant to add a comma there:
mycursor.execute(query, (value,))
# Creates a one-element tuple-^
I've got a wrapper I wrote around the sqlite3 module that lets me serialize access from multiple threads. It also lets me automatically migrate tables when I change their definition. I noticed when I drop a table and re-add it with more columns, I get an index out of range error. Something like this:
conn = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_COLNAMES)
curs = conn.cursor()
curs.execute("CREATE TABLE test (derp TEXT);"); conn.commit()
curs.execute("INSERT INTO test (derp) VALUES ('deedle');"); conn.commit()
print curs.execute("SELECT * FROM test;").fetchall()
curs.execute("DROP TABLE test;"); conn.commit()
curs.execute("CREATE TABLE test (derp TEXT, val REAL);"); conn.commit()
curs.execute("INSERT INTO test (derp) VALUES ('deedle');"); conn.commit()
print curs.execute("SELECT * FROM test;").fetchall()
conn.close()
Will print this:
[(u'deedle',)] Traceback (most recent
call last): File "test.py", line 23,
in <module>
print curs.execute("SELECT * FROM test;").fetchall() IndexError: list
index out of range
When executing the second SELECT statement. Does anyone know why this is?
Well, it works just fine for me
[(u'deedle',)]
[(u'deedle', None)]