Python to SQLite3 - python

I am making a project where I connect to a database with Python then update and change things. I have run into problems when trying to retrieve information.
I am using this code:
import sqlite3
conn = sqlite3.connect('Project.db')
print ("Opened database sucessfully")
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")
for row in cursor:
print ("ID = "), row[0]
print ("ResidentTitle ="), row[1]
print ("Name ="), row[2]
print ("done");
conn.close()
from this I am getting back the error:
Traceback (most recent call last):
File "C:/sqlite/Sqlplz.py", line 7, in <module>
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")
sqlite3.OperationalError: no such table: Residents
How can I resolve this error?

cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROMResidents")
-------------------------------------------------------------------^
You are missing space, you should update like that
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")

Problem is fixed, issue with a broken save file.

Related

Python MySQL Update from Excel file doesn't work

I am able to insert and replace the data in my MySQL table.
But I want to update the column dLieferdatum if the column sku equals cArtNr.
The Excel file looks as follows:
My Python Code:
cursor = connection.cursor()
query = """UPDATE d032683a.jll99_deliverytime_import SET dLieferdatum %s WHERE sku = %s"""
for r in range(1, sheet.nrows):
cArtNr = sheet.cell(r,1).value
dLieferdatum = sheet.cell(r,2).value
values = (dLieferdatum, cArtNr)
cursor.execute(query, values)
connection.commit()
cursor.close()
connection.close()
My Compiler (cygwin) error message:
Traceback (most recent call last):
File "sql_update.py", line 63, in
cursor.execute(query, values)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2020-05-29' WHERE sku = '11330342'' at line 1")
Many thanks and best regards.
I think you are missing an equal sign in the update statement and that is why you are getting the error. I think if you add equal sign then you should be fine.
Also,if I were you, I would print the query in the console to see what is the exact query that is being sent to database and also for testing might run that query directly in database.
UPDATE d032683a.jll99_deliverytime_import SET dLieferdatum = %s WHERE sku = %s
You print(query) should look like below:
UPDATE d032683a.jll99_deliverytime_import SET dLieferdatum = '2020-05-29' WHERE sku = '11330342'

PostgreSQL: Unable to drop a specific table named "user"

I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute("DROP TABLE user;")
conn.commit()
conn.close()
It spits out the following error
Traceback (most recent call last):
File "dev_psycog.py", line 20, in <module>
cur.execute("DROP TABLE user;")
psycopg2.ProgrammingError: syntax error at or near "user"
LINE 1: DROP TABLE user;
I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a reserved keyword?
Quote "user" as below
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute('DROP TABLE "user";')
conn.commit()
conn.close()
See here.
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-quotes (").

Python: How can I troubleshoot this Function?

I'm working on an application and currently focusing on the database area.
I have successfully setup functions that create databases and write to them, however right now I am trying to retrieve specific rows from the database however NO MATTER WHAT I TRY I always get a syntax error DESPITE my SQL query running successfully in in sqlite browser.
This is my trouble code:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM "working" WHERE "symbol" = 'aapl';')
print row
If I understand the code I've written, it should connect to "working.db" create a cursor for the database then for each row that match my query it should be printed to the console.
Can anyone please help shed some light on this?
Thank you!
Current Code Per comments below:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
print row
and the error output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from stock import *
File "/Users/ME/Documents/Code/Stocks/stock/database.py", line 61
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
Your string syntax is wrong:
c.execute('SELECT * FROM working WHERE symbol = "aapl"')

Qmark in pymysql query

I'm new to python, just moving from php5. I read about the qmark param notation to prepare a query but I get the following:
Traceback (most recent call last):
File "t.py", line 10, in <module>
cursor.execute("SELECT * FROM object WHERE otype = ?", ["user"])
File "/usr/local/lib/python3.4/site-packages/pymysql/cursors.py", line 130, in execute
query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting
Is that only for sqlite connector?
import sys
import pymysql
try:
connection = pymysql.connect(host="127.0.0.1", user="root", passwd="pass", db="xxx")
except:
sys.exit("Database connection error")
cursor = connection.cursor()
cursor.execute("SELECT * FROM object WHERE otype = ?", "user")
for row in cursor:
print(row)
cursor.close()
connection.close()
Yes. Unfortunately the DB-API specification left it up to each implementer to choose the parameter. pysqlite chose the ?, and MySQLdb chose %s. Since pymsql is a drop-in replacement for MySQLdb, it also uses %s.

MySQL SELECT from field in CSV in Python

I am currently having issues with performing a MySQL SELECT Query based on rows in a .csv file inside a python script;
#!/usr/bin/env python
import MySQLdb, csv, sys
db = MySQLdb.connect(host="hostname",
user="user",
passwd="password",
db="database")
cur = db.cursor()
customers=csv.reader(file("customers.csv"))
for row in customers(row):
cur.execute("select field from database.table where customernumber = %s;" % row)
cur.commit()
cur.close()
I am getting this;
Traceback (most recent call last):
File "script.py", line 17, in <module>
cur.execute("select field from database.table where field = %s;" % row)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['1598']' at line 1")
The first row in the .csv file is 1598.
For some reason it is encasing this entry with '['1598']' hence the mySQL query failing,
Any ideas why it is encasing it and how to stop it?
Thanks in advance!
I have renamed all mysql details to defaults for DPA Reasons
Ashley
First, you need to fix your csv reader logic. Then you need to pass the value as an argument to execute, commit() is done on the connection not the cursor and finally - you are closing your connection in the loop itself.
import csv
with open('customers.csv') as f:
reader = csv.reader(f)
rows = list(reader)
for row in rows:
cur.execute("select field from database.table where customernumber = %s;", (row[0],))
con.commit()
con.close()
try this,
for row in customers:
print row , row[0]
row[0] should be first column value.
Change executing the SELECT to something like this:
cur.execute("SELECT field FROM database.table WHERE customernumber = %s", (row[0],))
If row[0] has the number, otherwise which ever index has it, like row[4].
cur.execute("select field from database.table where customernumber = %s;" % row[0])
You need to pass row[0] instead of row. row is a list and row[0] is the first element of that list.

Categories

Resources