Python3 and Sqlite3 can't Insert - python-3.x

I am trying to write a function to do a simple insert.
Here is what I have tried so far
#! /usr/bin/env python3
#import
import sqlite3 as lite
#trying an insert version 1 (does nothing)
def createTableTask():
"""
Create a new table with the name Task
"""
#Connnection to the database and cursor creation
con = lite.connect('./exemple.sqlite')
con.row_factory = lite.Row
cur = con.cursor()
#that does nothing
try:
cur.execute('''CREATE TABLE Tasks (\
Name TEXT PRIMARY KEY, \
Description TEXT, \
Priority TEXT);''')
except lite.IntegrityError as error_SQLite:
print("error: "+ str(error_SQLite))
else:
print("No error has occured.")
con.close();
def insert1():
"""
insert a new task
"""
#Allocating variables data
taskName = 'finish code'
taskDescription = 'debug'
taskPriority = 'normal'
#Connnection to the database and cursor creation
con = lite.connect('./exemple.sqlite')
con.row_factory = lite.Row
cur = con.cursor()
#that does nothing
try:
with con:
cur.execute('''INSERT INTO Tasks (Name, Description, Priority) \
VALUES (?, ?, ?)''', (taskName, taskDescription, taskPriority))
except lite.IntegrityError as error_SQLite:
print("error: "+ str(error_SQLite))
else:
print("No error has occured. but no insert happend ?")
con.close();
def showResult():
"""
Show the result of the insert
"""
con = lite.connect('./exemple.sqlite')
con.row_factory = lite.Row
cur = con.cursor()
cur.execute\
('''SELECT * FROM Tasks ;''')
row = cur.fetchone()
while row:
print(row["Name"], ' | ', row["Description"], ' | ', \
row["Priority"])
row = cur.fetchone()
con.close();
#trying an insert version 2 (this one crash giving :Value error)
def insert2():
"""
insert a new task
"""
#Allocating variables data
taskName = 'finish code'
taskDescription = 'debug'
taskPriority = 'normal'
#Connnection to the database and cursor creation
con = lite.connect('./exemple.sqlite')
con.row_factory = lite.Row
cur = con.cursor()
queryInsert = ('''INSERT INTO Tasks (Name, Description, Priority) \
VALUES (?, ?, ?)''', (taskName, taskDescription, taskPriority))
try:
with con:
cur.execute(queryInsert)
except lite.IntegrityError as error_SQLite:
print("error: "+ str(error_SQLite))
else:
print("No error has occured.")
con.close();
def run():
createTableTask()
insert1()
showResult()
insert2()
showResult()
#calling section
run()
The problem is that none of the insert that I have made so far worked.
The first one does actualy nothing but has a correct syntax
The second one, well it crash.
Here is the output:
spark#spark-Razer-Blade-Pro:~/Documents/testing$ ./exemp.py
No error has occured.
No error has occured. but no insert happend ?
Traceback (most recent call last):
File "./exemp.py", line 98, in
run()
File "./exemp.py", line 94, in run
insert2()
File "./exemp.py", line 83, in insert2
cur.execute(queryInsert)
ValueError: operation parameter must be str
spark#spark-Razer-Blade-Pro:~/Documents/testing$ sqlite3 exemple.sqlite
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> SELECT * FROM Tasks;
sqlite>
I am looking for the most simple fix and maybe know what is wrong with my code. Because Right now I do not know what is going on with the no insert one. Normally it should, or am I missing something ?

queryInsert = ('''INSERT ...''', (taskName, taskDescription, taskPriority))
This makes queryInsert a tuple with two elements.
But to call the execute method, you need two separate parameters.
You could just unpack the tuple:
cur.execute(*queryInsert)
but it might be clearer to use two separate variables:
queryString = '''INSERT ...'''
queryParams = (taskName, taskDescription, taskPriority)
cur.execute(queryString, queryParams)

ok I got around my error. Just posting it because it might help others.
cur.execute() is a fonction that seek a query as it's first argument, than the other argument are the variables needed for the query.
step one: make the query into a variable without it's parameters
queryString = ''' INSERT INTO someTables rowName, rowName2 ... VALUES (?, ?);'''
there should be as much as ? as there are variables needed. in this exemple I need 2
queryValue1 = 'something'
queryValue2 = '123'
Step 2 to call and execute the query :
cur.execute(queryString, queryValue1, queryValue2)
this should be working without problem

Related

How can I use something stored in a DataBase? SQLite / Python

So, I am new at DataBases and I have a question. I first made a re-search in the internet but could not find anything or actually I could not understand correctly what they were explaining. Before starting with my question I want to say that I am currently working in a Discord Bot in Python as Main Language and I am trying to create a per-server-prefix system. I have already made it once but in .JSON format. Then I heard that using .JSON to save this kind of Data is not actually good so I moved to DataBases. Now, my question is:
I have stored the guild_id and prefix in my DB, how could I use that for a per-server-prefix system? I have not tried anything yet except writing the Code to store both Texts. I would really love if anyone could explain to me not just tell me the Code! Any answer will be appreciated <3.
Main.py:
def get_prefix(client, message):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is None:
return "/"
else:
client = commands.Bot(command_prefix = get_prefix)
Prefixes.py (COGS):
#commands.command()
#commands.has_permissions(administrator=True)
async def prefix(self, ctx, prefix=None):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = ?", ctx.guild.id)
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO prefixes(guild_id, prefix) VALUES(?,?)")
val = (ctx.guild.id, prefix)
await ctx.channel.send(f"{prefix}")
elif result is not None:
sql = ("UPDATE prefixes SET prefix = ? WHERE guild_id = ?")
val = (prefix, ctx.guild.id)
await ctx.channel.send(f"update `{prefix}`")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
That is pretty much the whole code. If you think anything should be changed or have any suggestions, answer in the comments!
All you need to do is, after the else, put return result. For example:
result = cursor.fetchone()
if result is None:
return "/"
else:
return result
cursor.fetchone() returns a tuple with each element requested in the row, as you only requested the prefix, it will contain just that (e.g: ("!",)) which is permitted as your command_prefix callable can return a string or tuple of strings.
Warning:
You may want to add a check to ensure that someone doesn't specify an empty string (A zero length string with nothing in it) as their prefix, otherwise your bot will attempt to run every message it sees as a command
References: discord.ext.commands.Bot.command_prefix

Python3 - IndexError not caught when using except

I'd like to catch any type of error in Python3.
I'm trying something like that:
try:
fields = line.split(' ')
...
<PostgreSQL query execution>
except psycopg2.Error:
conn.rollback()
QUERY = "UPDATE table SET error='sql'"
cur = conn.cursor()
cur.execute(QUERY)
conn.commit()
cur.close()
continue
except:
conn.rollback()
e="generic"
QUERY = "UPDATE table SET error='generic'"
cur = conn.cursor()
cur.execute(QUERY)
conn.commit()
cur.close()
continue
But I noted that, for example, an IndexError is not caught and the script fails.
What's wrong?
Thanks!
This happens when a new exception occurs in the except block.
For example:
try:
print('foo')
raise ValueError
except:
print('noes!')
print(1/0)
Will exit with divide by zero exception.
In order to see if it is so, we need more of actual code from you, particularly both of the except blocks.
If you want to make sure you catch "any" exception, make sure your except blocks are unexceptional.

Parameterized SQLite Table Insertion via Python?

I have been trying to get a function working to insert a name in to table of users, but for some reason it just isn't working.
import sqlite3
def CreateUser(Name):
try:
sqliteConnection = sqlite3.connect('Expenses.db')
cursor = sqliteConnection.cursor()
make_user = """INSERT INTO Users (Name) VALUES(?);"""
cursor.execute(make_user, Name)
sqliteConnection.commit()
print()
print('User Successfully Created')
print()
# cursor.close()
except sqlite3.Error as error:
print('Failed to Create User', error)
print()
finally:
if (sqliteConnection):
sqliteConnection.close()
print()
escape = input('Press any key to continue.')
Name = input('> ')
CreateUser(Name)
But for some reason it takes the input string and converts it to the sum of every letter in the string. Inputting a name that is a single digit or letter works, but as soon as it's two or more letters, it throws an error of having too many bindings.
I have tried several variations but I just can't seem to get it working. Can anyone point me in the right direction?
Try binding a tuple containing the name, instead of passing the name variable directly:
sqliteConnection = sqlite3.connect('Expenses.db')
cursor = sqliteConnection.cursor()
make_user = """INSERT INTO Users (Name) VALUES(?);"""
cursor.execute(make_user, (Name,)) # change is here
sqliteConnection.commit()

Data base not showing in python

so whenever I try to run my code it gives me this error:
Error screenshot
this is my code if you guys would like to tell me what is wrong with it it would help and if you guys can fix it would be nice as well because I have been trying to fix it for about 3 weeks now.
Code:
import sqlite3
conn = sqlite3.connect('GVP - Eruptions Trial 1.2.db')
DATABASE_FILE = "backpack.db"
"functions"
def show_backpack(connection):
'''nicely print the backpack info'''
cursor = connection.cursor()
sql = "Select * FROM contents"
cursor.execute(sql)
results = cursor.fetchall()
print(f"{'Name':<20}{'Description':<60}")
for item in results:
print(f"{item[1]:<20}{item[2]:<60}")
def add_item(connection,item_name,item_description):
'''add item to backpack database'''
cursor=connection.cursor()
sql = "INSERT INTO contents(name,description) VALUES (?,?)"
cursor.execute(sql,(item_name,item_description))
connection.commit()
with sqlite3.connect(DATABASE_FILE) as connection :
show_backpack(connection)
#add item
add_item(connection,"fish","me no likey")
show_backpack()

Postgres Function - run from Python, no records inserted

I'm trying to use Python to run a PostgreSQL function that inserts data from one table into another. If I run the function in pgAdmin it works, but if I run it through Python I get the return value, which says it's executed, but it doesn't insert any records.
Here is my Python code
import psycopg2
from parse_config import fn_parse_config
def run_function():
conn = None
try:
# read database configuration
login_params = fn_parse_config("etl_process.ini", "psycopg_login")
# connect to the PostgreSQL database
conn = psycopg2.connect(**login_params)
# create a cursor object for execution
cur = conn.cursor()
# another way to call a stored procedure
#cur.execute("SELECT * FROM usp_test();")
cur.callproc('usp_test')
# process the result set
row = cur.fetchone()
while row is not None:
print(row)
row = cur.fetchone()
# close the communication with the PostgreSQL database server
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
run_function()
Here is my function
CREATE OR REPLACE FUNCTION usp_test()
RETURNS integer AS $$
BEGIN
INSERT INTO staging_raw_file (Site,
StyleCode)
select CAST(a.Site as VARCHAR(10)),
CAST(a.StyleCode as VARCHAR(30))
from import_raw_file a;
return 5;
END; $$
LANGUAGE plpgsql;
Found the answer, it needs autocommit setting
conn = psycopg2.connect(**login_params)
conn.autocommit = True
without that it doesn't actually run the insert, but it will return results from just a select without that

Resources