Returning a database with locations - python

I think I have the right idea to solve this function, but I'm not sure why I get this error when I test it. Can anyone please help me fix this?
Error: conn = sqlite3.connect(db)
sqlite3.OperationalError: unable to open database file
Desired Output:
>>> get_locations(db, 'ANTA01H3F')
[('ANTA01H3F', 'LEC01', 'AA112'), ('ANTA01H3F', 'LEC01', 'SY110'), ('ANTA01H3F', 'LEC02', 'AC223')]
def get_locations(db, course):
'''Return the course, section and locations of the exam for the given course.'''
return run_query('''SELECT Courses.Course, Courses.Sections, Room.Locations
FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = ?''', [course])

This is too much abstract. ;)
See run_query() from where it is getting the value of db (sqlite database file name) to run queries. It is not getting correct file name that you are expecting.
You are calling the function wrong, it accepts db and sql statement string:
return run_query(db, "SELECT Courses.Course, Courses.Sections, Locations.Room " \
" FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = '{}'".format(course))

Related

Error executing cursor.execute when quotes are required

fairly new to SQL in general. I'm currently trying to bolster my general understanding of how to pass commands via cursor.execute(). I'm currently trying to grab a column from a table and rename it to something different.
import mysql.connector
user = 'root'
pw = 'test!*'
host = 'localhost'
db = 'test1'
conn = mysql.connector.connect(user=user, password=pw, host=host, database=db)
cursor = conn.cursor(prepared=True)
new_name = 'Company Name'
query = f'SELECT company_name AS {new_name} from company_directory'
cursor.execute(query)
fetch = cursor.fetchall()
I've also tried it like this:
query = 'SELECT company_name AS %s from company_directory'
cursor.execute(query, ('Company Name'),)
fetch = cursor.fetchall()
but that returns the following error:
stmt = self._cmysql.stmt_prepare(statement)
_mysql_connector.MySQLInterfaceError: 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 '? from company_directory' at line 1
I'm using python and mySQL. I keep reading about database injection and not using string concatenation but every time I try to use %s I get an error similar to the one below where. I've tried switching to ? syntax but i get the same error.
If someone could ELI5 what the difference is and what exactly database injection is and if what I'm doing in the first attempt qualifies as string concatenation that I should be trying to avoid.
Thank you so much!
If a column name or alias contains spaces, you need to put it in backticks.
query = f'SELECT company_name AS `{new_name}` from company_directory'
You can't use a placeholder for identifiers like table and column names or aliases, only where expressions are allowed.
You can't make a query parameter in place of a column alias. The rules for column aliases are the same as column identifiers, and they must be fixed in the query before you pass the query string.
So you could do this:
query = f"SELECT company_name AS `{'Company Name'}` from company_directory'
cursor.execute(query)

Error in extracting DDL for functions in DB2

I used the below statement to extract the ddl for particular function using python in DB2.
Function name = 'DEPTEMPLOYEES'
DDL = "select text from syscat.routines where routineschema = {}
and routinename = {} and routinetype = 'F'".format(user_schema,objs.upper())
cursor.execute(DDL)
But when I tried to execute this statement am getting an error.
ibm_db_dbi::ProgrammingError: SQLNumResultCols failed: [IBM][CLI
Driver][DB2/NT64] SQL0206N "DEPTEMPLOYEES" is not valid in the
context where it is used. SQLSTATE=42703\r SQLCODE=-206
Can someone please help me to solve this error
Have you tried something like this, adding single quotes around the strings?
DDL = "select text from syscat.routines where routineschema = '{}'
and routinename = '{}' and routinetype = 'F'".format(user_schema,objs.upper())
cursor.execute(DDL)
Based on the error it seems that your parameters was printed and the quotes were missing. This turned the parameter into a keyword, hence the error message.

Compile query from raw string (without using .text(...)) using Sqlalchemy connection and Postgres

I am using Sqlalchemy 1.3 to connect to a PostgreSQL 9.6 database (through Psycopg).
I have a very, very raw Sql string formatted using Psycopg2 syntax which I can not modify because of some legacy issues:
statement_str = SELECT * FROM users WHERE user_id=%(user_id)s
Notice the %(user_id)s
I can happily execute that using a sqlalchemy connection just by doing:
connection = sqlalch_engine.connect()
rows = conn.execute(statement_str, user_id=self.user_id)
And it works fine. I get my user and all is nice and good.
Now, for debugging purposes I'd like to get the actual query with the %(user_id)s argument expanded to the actual value. For instance: If user_id = "foo", then get SELECT * FROM users WHERE user_id = 'foo'
I've seen tons of examples using sqlalchemy.text(...) to produce a statement and then get a compiled version. I have that thanks to other answers like this one or this one been able to produce a decent str when I have an SqlAlchemy query.
However, in this particular case, since I'm using a more cursor-specific syntax %(user_id) I can't do that. If I try:
text(statement_str).bindparams(user_id="foo")
I get:
This text() construct doesn't define a bound parameter named 'user_id'
So I guess what I'm looking for would be something like
conn.compile(statement_str, user_id=self.user_id)
But I haven't been able to get that.
Not sure if this what you want but here goes.
Assuming statement_str is actually a string:
import sqlalchemy as sa
statement_str = "SELECT * FROM users WHERE user_id=%(user_id)s"
params = {'user_id': 'foo'}
query_text = sa.text(statement_str % params)
# str(query_text) should print "select * from users where user_id=foo"
Ok I think I got it.
The combination of SqlAlchemy's raw_connection + Psycopg's mogrify seems to be the answer.
conn = sqlalch_engine.raw_connection()
try:
cursor = conn.cursor()
s_str = cursor.mogrify(statement_str, {'user_id': self.user_id})
s_str = s_str.decode("utf-8") # mogrify returns bytes
# Some cleanup for niceness:
s_str = s_str.replace('\n', ' ')
s_str = re.sub(r'\s{2,}', ' ', s_str)
finally:
conn.close()
I hope someone else finds this helpful

Selecting record from mySQL via cursors returns an None object

I am writing a script in python 3.x using mysqlconnector.
What I am trying to achieve right now is to check if there is a record inside my db which may be a duplicate to the one I am analyzing right now.
I came up with such code:
def fill_data(self, db_name, data):
cursor = self.cnx.cursor(buffered=True)
isDuplicate = cursor.execute(("SELECT destination FROM {0} WHERE destination = '{1}';")
.format(db_name, data['destination']))
print(cursor.statement)
self.commit()
print(isDuplicate is None)
Though I still get isDuplicate as None object. I tried to check via cursor.statement what statement is being passed to my db: it turned out that while in script I get None obj while passed in db that query works fine.
I also tried SELECT COUNT(1) FROM db_name which also gave me different results.
I am out of ideas: maybe you guys can help me out?
Update:
The solution that works for me was:
q = ("SELECT * FROM {0} WHERE destination = %s AND countryCode = %s AND prefix = %s")
.format(db_name)
cursor.execute(q, (data['destination'], data['country_code'], data['prefix']))
self.cnx.commit()
isDoubled = cursor.fetchone()
So at the end of the day it was all about fetching data from the cursor :)
Maybe the reason of your issue is the way you use execute() method.
Try to make some changes and see what is printed out:
def fill_data(self, db_name, data):
cursor = self.cnx.cursor(buffered=True)
q = 'SELECT count(*) FROM {} WHERE destination = %s'.format(db_name)
duplicate_count = cursor.execute(q, (data['destination'], )).fetchall()
print(duplicate_count)
Why should I provide query parameters this way? (article is on psql, but the core principles are the same as in mysql)
update
If you are still receiving "NoneType" object has no atribute "fetchall", then the error is probably here:
cursor = self.cnx.cursor(buffered=True)
Looks like you are not creating cursor at all. I can take a look at it if you post some code about cnx creation.

SQLite INNER JOIN in python: sqlite3.OperationalError: no such column:

I'm having an issue with SQLite in python. The following code doesn't appear to work due to the error
sqlite3.OperationalError: no such column: Company
I'm trying to gather data from both of the tables and display them back to the user using tabulate but cannot proceed and I cannot figure out how to solve this problem. The solution is probably simple but due to my limited programming knowledge I'm unsure how to proceed.
Here's the code:
def view_all_by_CompID(data):
with sqlite3.connect("Clients.db") as db:
cursor = db.cursor()
cursor.execute("""SELECT CompanyID, Forename, Surname, eMail
FROM Clients
JOIN Company
ON Clients.CompanyID = Company.CompanyID
WHERE CompanyID = ?""",(data,))
ViewData = cursor.fetchall()
DataTableCompAndClient([ViewData])
db.commit()
I am unsure why this happens as I'm certain that both tables exist and that (I believe) am calling them correctly. I don't know why it keeps giving me the error so any help would be appreciated. Here's a few details about the code:
Clients.db = The name of the database file
Clients = A table where client information is held
Company = A table where company information is held
CompanyID = A specified Company ID number present in both tables
I've looked at a variety of examples on this site but I can't seem to solve the issue. Any advice would be appreciated.
I have fixed the problem with the help of a friend. There were a few missing lines of code which needed entering, which are the following:
def view_all_by_CompID(data):
with sqlite3.connect("Clients.db") as db:
cursor = db.cursor()
cursor.execute("""SELECT Clients.CompanyID, Clients.Forename, Clients.Surname, Clients.eMail, Company.CompanyID, Company.CompanyName
FROM Clients
INNER JOIN Company
ON Clients.CompanyID = Company.CompanyID
WHERE Clients.CompanyID = ?""",(data,))
ViewData = cursor.fetchall()
DataTableCompAndClient([ViewData])
db.commit()

Categories

Resources