Update statement for sqlite in python not working - python

I have made a simple for loop program which takes info from the user and updates the Database in sqlite. However my program does not update the DB, it just plainly ignores it. I have tried solutions from all over the net and haven't found anything just yet. I've given just the relevant stuff everything else works just fine.
query ="Alpha"
string = "Beta"
CreateDB = sqlite3.connect('check.db')
querycurs = CreateDB.cursor()
def createTable():
querycurs.execute('''CREATE TABLE Data1
(id INTEGER PRIMARY KEY, q TEXT, info TEXT)''')
createTable()
def addCust(q,info):
querycurs.execute('''INSERT INTO Data1 (q,info)
VALUES (?,?)''',(q,info))
addCust(query,string)
for i in range (1, 5):
string = input('What would you like to enter?: ')
querycurs.execute('UPDATE Data1 SET info =? WHERE q =?',(string,query))
CreateDB.commit()
If you get any syntax errors running this program its fine cause i edited the program so i could put it online. It's only the UPDATE statement you'd need to worry about. Cheerio.

Works fine for me. I suggest you change input() to raw_input() to enforce string data.

Related

Python mysql.connector insert does not work

I work with the Python mysql.connector for the first time and I am not able to create a working insert statement.
This is the table:
'CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255));'
I am trying to insert a variable as title while the id should be auto incremented. I have tried multiple solutions but it simply won't work.
def insert_product(title: str):
insert_product_query = 'INSERT INTO products (title) VALUES (%s);'
cursor.execute(insert_product_query, (title,))
This runs without any error, but the insert is not working. It does nothing. I tried multiple versions of this, with '?' instead of '%s' and without a tuple but it won't work.
Another solution I tried is this:
def insert_product(title: str):
insert_product_query = f'INSERT INTO products (title) VALUES (\'{title}\')'
print(insert_product_query)
cursor.execute(insert_product_query)
I printed the insert statement and when I copy paste it directly into the database it works perfectly, so I don't have any idea why it is not working out of the python code as it is not producing any errors.
I found many similar problems but none of the solution worked for me.
I hope someone can help me as I might overlook something obvious.
Thanks in advance!
Python's connector disables autocommit by default (as a reasonable library would do!). You need to explicitly commit after you perform a DML statement:
con.commit() # Assuming con is the name of the connection variable

How to format postgreSQL queries in a python script for better readability?

I have another question that is related to a project I am working on for school. I have created a PostgreSQL database, with 5 tables and a bunch of rows. I have created a script that allows a user to search for information in the database using a menu, as well as adding and removing content from one of the tables.
When displaying a table in PostgreSQL CLI itself, it looks pretty clean, however, whenever displaying even a simple table with no user input, it looks really messy. While this is an optional component for the project, I would prefer to have something that looks a little cleaner.
I have tried a variety of potential solutions that I have seen online, even a few from stack overflow, but none of them work. Whenever I try to use any of the methods I have seen and somewhat understand, I always get the error:
TypeError: 'int' object is not subscriptable
I added a bunch of print statements in my code, to try and figure out why it refuses to typecast. It is being dumb. Knowing me it is probably a simple typo that I can't see. Not even sure if this solution will work, just one of the examples I saw online.
try:
connection = psycopg2.connect(database='Blockbuster36', user='dbadmin')
cursor = connection.cursor()
except psycopg2.DatabaseError:
print("No connection to database.")
sys.exit(1)
cursor.execute("select * from Customer;")
tuple = cursor.fetchone()
List_Tuple = list(tuple)
print("Customer_ID | First_Name | Last_Name | Postal_Code | Phone_Num | Member_Date")
print(List_Tuple)
print()
for item in List_Tuple:
print(item[0]," "*(11-len(str(item[0]))),"|")
print(item)
print(type(item))
print()
num = str(item[0])
print(num)
print(type(num))
print(str(item[0]))
print(type(str(item[0])))
cursor.close()
connection.close()
I uploaded the difference between the output I get through a basic python script and in the PostgreSQL CLI. I have blocked out names in the tables for privacy reasons. https://temporysite.weebly.com/
It doesn't have to look exactly like PostgreSQL, but anything that looks better than the current mess would be great.
Use string formatting to do that. You can also set it to pad right or left.
As far as the dates use datetime.strftime.
The following would set the padding to 10 places:
print(”{:10}|{:10}".format(item[0], item[1]))

Using SQLite3 with python

I just started learning SQLite3 for python today, and I'm having trouble figuring out why this won't work.
import sqlite3, os
if not os.path.isfile("G:\\Python\\My first database.db"):
dtabse = sqlite3.connect("G:\\Python\\My first database.db")
cursr = dtabse.cursor()
cursr.execute("""CREATE TABLE Students
(first_name text,
surname text,
DOB text,
Form text)
""")
cursr.execute(""" INSERT INTO Students
VALUES ("Dave", "Edwards", "16", "11AB")""")
dtabse.commit()
dtabse.close()
else:
dtabse = sqlite3.connect("G:\\Python\\My first database.db")
cursr = dtabse.cursor()
print(cursr.fetchall())
In a powerpoint I was viewing, it said fetchall() should retrieve everything and display it. On the first go of this program it won't find a file in this directory, so the if area gets executed. When I next run the program the else area gets executed.
That much works, on the first go the program ends and begins. On the second go it prints an empty list, when I was expecting the table. I checked the database file and the data is there, so why can't I print it?
You need a SELECT statement to retrieve the data you want.

Python cx_Oracle Update

In my Python code when I ask the user to input a string to SELECT, it works but when I try the UPDATE using the same input doesn't allow me to execute
Here is my code after the connection has been successfully done
curs = connection.cursor()
str_input1 = str(input("Input : "))
str_input2 = str(input("Input : "))
statement = "UPDATE table SET variable1 = "+str_input1+" WHERE name = "+str_input2
curs.execute(statement)
connection.commit
In theory this following code should work and update the variable, but instead I get the error at line curs.execute(statement) saying
cx_Oracle.DatabaseError: ORA-00904: John: invalid identifier
John was the str_input2 for where clause
Maybe its the format that was giving me an error but I'm not too sure.
Can someone point out what was the problem with my code?
The error is because you're not quoting the values. You'd get the exact same error from a SELECT statement.
These statements search for rows where the name column matches the string John:
SELECT * FROM table WHERE name = "John"
UPDATE table SET variable1 = "Hi" WHERE name = "John"
These statements search for rows where the name columns matches the John column—and if there is no John column, that's an error:
SELECT * FROM table WHERE name = John
UPDATE table SET variable1 = "Hi" WHERE name = John
So, you could fix this by just putting quotes around the values.
But you really, really, really shouldn't. This opens you up to SQL injection attacks, and stupid bugs where you don't quote or escape special characters properly, and performance problems where the database engine can't tell that you're running the same query over and over, and so on.
What you want to do is to use SQL parameters, instead of trying to format the string. I don't remember which parameter style cx_Oracle uses, but you can just import cx_Oracle; print(cx_Oracle.paramstyle), and look it up in the table to find out. And then do something like:
statement = "UPDATE table SET variable1 = :v WHERE name = :n"
curs.execute(statement, {'v': str_input1, 'n': str_input2})
Also, a few side notes:
connection.commit doesn't do anything; you're just referencing the commit method, not calling it. You need parentheses: connection.commit()
str(input()) is pointless. The input function always returns a string, so there's no reason to call str on it. (Unless you're using Python 2.x, in which case you should be using raw_input(), which returns a string, instead of using input to eval the string—opening up the same kinds of security problems as the SQL injection attack above—only to convert it back to a string.)

SQLAlchemy / Python / Pyramid Write To Database Issue

The problem:
I am working on a bit of code that is meant to create a new record in a linking table. The linking table has a primary key that is an auto number, the other two fields are VARCHAR with a length of 10.
The issue I'm having is I cannot seem to get partID into the table. If you look at the sql output you can clearly see it write None and u'1' (the orderID) to the table. So that tells me its recieving the orderID just fine. Also you can see that I did a print to find out what is inside my variable before passing it to the new object. It has 3 in it which is the correct partId. Somewhere between creating the new object and writing to the table it passes a null.
I've tried to cast it, Ive tried different ways of pulling the partID from the database, etc and I cannot for the life of me figure out what is wrong.
The code:
def updateOrderParts_view(request):
part = None
partToOrder = None
idnum = None
part = DBSession.execute(\
"SELECT partID "+\
"FROM tblParts "+\
"WHERE partName = " + "'" +request.POST['partName'] +"'").fetchone()
print "<---DEBUG--->"
print part['partID']
partToOrder = PartsByOrder(part['partID'], request.POST['orderID'])
DBSession.add(partToOrder)
return{}
The terminal output:
<---DEBUG--->
3
2013-04-24 08:14:47,985 INFO [sqlalchemy.engine.base.Engine][Dummy-2] INSERT INTO "tblPartsByOrder" ("partID", "orderID") VALUES (?, ?)
2013-04-24 08:14:47,985 INFO [sqlalchemy.engine.base.Engine][Dummy-2] (None, u'1')
2013-04-24 08:14:47,986 INFO [sqlalchemy.engine.base.Engine][Dummy-2] COMMIT
I would appreciate any thoughts or comments on this issue
Thanks for your time
First, I would look at doing the SQL lookup a little different, if you can. (I guess it depends, do you have a model based on "tblParts"? I'm going to use an example assuming there is a model object "Part"):
part = DBSession.query(Part.partID).filter(Part.partName == request.POST['partName']).first()
From there, I'm rusty on the exact syntax but I think you could do something like
print "<---DEBUG--->"
print part
partToOrder = PartsByOrder(part, request.POST['orderID'])
DBSession.add(partToOrder)
return{}
You might need to case "part" to a string (str(part)) if it's a casting problem.
Good luck,

Categories