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

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()

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)

Creating a table based on input, if input doesnt exist in db file creates a table, if exists, writes ID to it

I'm trying to make a program in Python that requests an input and if the table in the DB exists, writes to it, and if it doesn't, creates it.
Here is the existing code:
connection = sqlite3.connect('AnimeScheduleSub.db')
cursor = connection.cursor()
anime_id = input('enter server id')
discord_user_id = int(input('Enter token'))
try:
cursor.execute("SELECT * FROM {}".format(anime_id))
results = cursor.fetchall()
print(results)
except:
command1 = f"""CREATE TABLE IF NOT EXISTS
{anime_id}(discord_user_id INTEGER)"""
cursor.execute(command1)
Basically, what it's doing (or what I'm trying to achieve) is the try loop is meant to check if the anime_id table exists. The except loop is meant to create the table if the try loop failed.
But it doesn't work, and I have no idea why. Any help would be much appreciated.
command1 = f"""CREATE TABLE IF NOT EXISTS
A{anime_id}(discord_user_id INTEGER)"""
Creating table name with just numbers are not supported by sql.
You should start with a letter and then use numbers.
You should "ask" the DB if the table is there or not.
Something like the below.
anime_id = input('enter server id')
SELECT name FROM sqlite_master WHERE type='table' AND name='{anime_id}';

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.

Returning a database with locations

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))

querying mysql database in python where table is a variable

I am aware this may be a duplicate post. However I have looked at the other posts and cant figure it out in my case.
from configdata import configdata
from dbfiles.dbconnect import connection
c,conn = connection()
table = configdata()[4]
userid = 'jdeepee'
value = c.execute("SELECT * FROM %s WHERE userid = (%s)" % (table), userid)
print(value)
I think the code is self explanatory. But essentially what I am trying to do is query a MySQL database based on a variable for the integer and userid. I believe my syntax is wrong not sure how to fix it however. Help would be great.
Try this:
value = c.execute("SELECT * FROM {} WHERE userid = %s".format(table), (userid,))
Basically, you need to interpolate the table name into the query first, then pass any query parameters to .execute() in a tuple.

Categories

Resources