Python - MySQL SELECT query with dynamic table name - python

I am trying to fetch all the rows from the MySQL DB in Python. How to fetch all row from the table, when the table name is variable?
Here is a method that I wrote, however I am getting error while running it.
def get_rows(self, table_name):
cursor = self.conn.cursor()
query = ("SELECT * "
"FROM %s ")
try:
cursor.execute(query, (table_name,))
value = cursor.fetchall()
finally:
cursor.close()
return value
And I am getting the following error:
AttributeError: 'NoneType' object has no attribute 'cursor'
I tried the similar way in WHERE clause and it worked fine.

You have a problem with conn object.
'NoneType' object has no attribute 'cursor' means conn is None, probably because it wasn't established during the __ init __ call.

You can't dynamically bind object names (here you're attempting to bind a table name) or syntactic constructs to a query. If you wish to have such a behavior you'd have to resort to string manipulation, meaning you're forfeiting all the security advantages prepared statements offer:
query = ("SELECT * FROM %s" % table_name)
try:
cursor.execute(query, ())

Related

Python MySQL not reading from database

Python unable to read from MySql database. Connectivity works but no results returned
import mysql.connector
cnx = mysql.connector.connect(user='user', password='pwd',host='<host>', port='<port>',database='mydb')
cursor = cnx.cursor()
print("Connection success")
query = ("SELECT * from users")
cursor.execute(query)
for (row) in cursor:
print(row)
print("Print complete")
cursor.close()
cnx.close()
I get below result
Connection success
Print complete
If I add below line
rows=cursor.fetchall()
I get below error
InterfaceError: No result set to fetch from.
I have checked from MySql workbench and I get results from above query.
EDIT: The question is not about fetchall, even without fetchall I don't see any results.
EDIT 2:
Few Observations:
If I try with incorrect password, I get Access Denied error.
If I try with incorrect table name (with correct password) I get
error that table doesn't exist.
If I add below line before the for loop
print(len(cursor.description))
I get below error
TypeError: object of type 'NoneType' has no len()

I can't access this variable outside the function that will be used for database connection

I am trying to access cursor outside the function dbconnect(). But I am getting this error "AttributeError: 'function' object has no attribute 'cursor'"
It would be really great if somebody could fix it. I am trying to make a program for school project. Code is given below.
import mysql.connector as mysql
def dbconnect():
db = mysql.connect(host='',
database='',
user='',
password='')
cursor = db.cursor()
return cursor
query = "select name,atomic_weight from elements where atomic_number = 8"
dbconnect.cursor.execute(query)
result = dbconnect.cursor.fetchall()
print(result)
cursor = dbconnect()
cursor.execute(query)
result = cursor.fetchall()

How to create a database with psycopg2 using execute() second argument?

I'm trying to create a database with the name a user will provide. As far as I know the correct way is to use the second argument of execute().
So I did as follows:
import psycopg2
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE %s ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(query, (name,))
cursor.close()
conn.close()
And I got this error:
psycopg2.errors.SyntaxError: syntax error at or near "'stackoverflow_example_db'"
LINE 1: CREATE DATABASE 'stackoverflow_example_db' ;
I need to do this statement avoiding SQL injection, so using the second argument is a must.
You can't pass values as second argument of execute(), if the statement is a CREATE DATABASE one.
As pointed out by unutbu one way to approach this is using the psycopg2.sql submodule and use identifiers to build the statement avoiding SQL injection.
The code:
import psycopg2
from psycopg2 import sql
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE {} ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(sql.SQL(query).format(
sql.Identifier(name)))
cursor.close()
conn.close()
Other aditional observations:
format() do not work with %s, use {} instead
Autocommit mode is a must for this statement to work
The specified connection user needs creation privileges

Python sqlite3 cursor has no attribute commit

When I run this code:
path = '~/Scripts/wallpapers/single.png'
conn = sqlite3.connect('/Users/Heaven/Library/Application Support/Dock/desktoppicture.db')
cur = conn.cursor();
cur.execute("insert into data values ('" + path + "');")
cur.commit()
I receive the following error
AttributeError: 'sqlite3.Cursor' object has no attribute 'commit'
and I have absolutely no idea why.
commit() is a member method of sqlite3.Connection not sqlite3.Cursor. Here it is in the docs.
From the answer from sir_charles804 (sorry not enough points to add this as comment) follows it should be:
conn.commit()
instead of
cur.commit()
It's
conn.commit()
conn.close() //if you intend to close it afterwards
Explanation:
The cursor is only used to pass instructions to sqlite, while you have to commit or close with the instance you've made to connect to your database.

sqlite attribute execute is read-only

I am using sqlite to create and connect to a sqlite db foo.db
When I try to do an insert into the DB. I get the following AttributeError
AttributeError: 'sqlite3.Cursor' object attribute 'execute' is read-only
I can't seem to find any information on this error. Does anyone have any idea what this exception means?
I am using python 2.7 with virtualenv.
The following is the code I am trying to execute assume date is a string.
username = 'user'
pwdhash = some_hash_function()
email = 'user#foo.com'
date = '11/07/2011'
g.db = sqlite3.connect('foo.db')
cur = g.db.cursor()
cur.execute = ('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
g.db.commit()
g.db.close()
Thanks
You're trying to modify an attribute of the cursor. You want to call a method of the cursor.
It should be
cur.execute('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
Not
cur.execute = ('insert ...
Seems to be a simple syntax error.
You are trying to set a value to the command execute while you have just to call it:
remove the '=' and it should be fine.

Categories