MySQL query returns data (u'example',) - python

I'm using a mysql lib on python, and when I try to do this query:
SELECT product FROM database1.contacts WHERE contact="%s" % (contact)
I get this:
(u'example',)
But I expect this:
example
Here is my code:
import mysql.connector
db_user = "root"
db_passwd = ""
db_host = "localhost"
db_name = "database1"
connector = mysql.connector.connect(user=db_user, password=db_passwd, host=db_host, database=db_name,
buffered=True)
cursor = connector.cursor()
contact = "943832628"
get_product_sql = 'SELECT product FROM database1.contacts WHERE contact="%s"' % (contact)
cursor.execute(get_product_sql)
for product in cursor:
print product

You are printing the whole row; print just the first column:
for product in cursor:
print product[0]
or use tuple unpacking in the loop:
for product, in cursor:
print product

Related

How to include a variable in mysql connectivity query?

my_connect = mysql.connector.connect(
host="localhost",
user="xyz",
passwd="xyz",
database="tracking"
)
my_conn = my_connect.cursor()
x = input("enter name")
query="SELECT * FROM trackingtable WHERE Customer_Name = \"x\"";
print(query)
my_conn.execute(query)
my_conn.close()
Query printed statement
How do i get the proper query using the input from user? I tried using placeholders but I couldn't get them to work
Try:
query = f"SELECT * FROM trackingtable WHERE Customer_Name = {x}"
It's an f-string in which you can plug in variables via {}.
If you need the "s inside the query:
query = f'SELECT * FROM trackingtable WHERE Customer_Name = "{x}"'
Do you need the ; at the end?

Send a Wildcard Characters in python sql query through %s

Code looks like this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = """SELECT * FROM customers WHERE address LIKE '%way%'"""
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This will select all the records whose address contain care like "way".
How to insert the wildcard dynamically by using %s
Basically I want to know how to use %s instead of 'way' in python so that the code will be more flexible.
try like below
query ="SELECT * FROM customers WHERE\
address LIKE '%"+variable+"%'"
Try escaping the percentage by doubling them.
>>> res = """SELECT * FROM customers WHERE address LIKE '%%%s%%'""" % ('way')
>>> res
"SELECT * FROM customers WHERE address LIKE '%way%'"

python: update mysql table

I am trying to update a mysql table with variable names. Below is the code that is not working for me:
import mysql.connector
conn= mysql.connector.connect(
host=host,
user=user,
passwd=password,
database=database
)
cur = conn.cursor()
cur.execute("update player_list set country = '%s', region = '%s',name = '%s' where id = %s "
% (country, region,name, id))
Running the "cur execute" line returns the following error:
mysql.connector.errors.InternalError: Unread result found
The ID column is an integer if it has any importance.
I don't see any code here how you've created your cursor, but looks like you need to specify buffered mode for your sql class to read.
Please, refer to official documentation and change your code to use buffer=True while creating your cursor and use it afterwards.
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorbuffered.html
Try
with conn.cursor() as cur:
sql = "update player_list set country = '%s', region = '%s',name = '%s' where id = %s" % (country, region,name, id)
cur.execute(sql)
conn.commit()
and add buffered = True into your conn like
connection = mysql.connector.connect([...], buffered = True)

Replace L, in SQL results in python

I'm running pyodbc connected to my db and when i run a simply query I get a load of results back such as
(7L, )(12L,) etc.
How do I replace the the 'L, ' with '' so I can pass the ids into another query
Thanks
Here's my code
import pyodbc
cnxn = pyodbc.connect('DSN=...;UID=...;PWD=...', ansi=True)
cursor = cnxn.cursor()
rows = cursor.execute("select id from orders")
for row in rows:
test = cursor.execute("select name from customer where order_id = %(id)s" %{'id':row})
print test
Use parameters:
...
test = cursor.execute("select name from customer where order_id = ?", row.id)
...
The L after the number indicates that the value is a long type.

Using dict_cursor in django

To get a cursor in django I do:
from django.db import connection
cursor = connection.cursor()
How would I get a dict cursor in django, the equivalent of -
import MySQLdb
connection = (establish connection)
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)
Is there a way to do this in django? When I tried cursor = connection.cursor(MySQLdb.cursors.DictCursor) I got a Exception Value: cursor() takes exactly 1 argument (2 given). Or do I need to connect directly with the python-mysql driver?
The django docs suggest using dictfetchall:
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
Is there a performance difference between using this and creating a dict_cursor?
No there is no such support for DictCursor in Django.
But you can write a small function to that for you.
See docs: Executing custom SQL directly:
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
>>> dictfetchall(cursor)
[{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
Easily done with Postgres at least, i'm sure mysql has similar ( Django 1.11)
from django.db import connections
from psycopg2.extras import NamedTupleCursor
def scan_tables(app):
conn = connections['default']
conn.ensure_connection()
with conn.connection.cursor(cursor_factory=NamedTupleCursor) as cursor:
cursor.execute("SELECT table_name, column_name "
"FROM information_schema.columns AS c "
"WHERE table_name LIKE '{}_%'".format(app))
columns = cursor.fetchall()
for column in columns:
print(column.table_name, column.column_name)
scan_tables('django')
Obviously feel free to use DictCursor, RealDictCursor, LoggingCursor etc
The following code converts the result set into a dictionary.
from django.db import connections
cursor = connections['default'].cursor()
columns = (x.name for x in cursor.description)
result = cursor.fetchone()
result = dict(zip(columns, result))
If the result set has multiple rows, iterate over the cursor instead.
columns = [x.name for x in cursor.description]
for row in cursor:
row = dict(zip(columns, row))
The main Purpose of using RealDictCursor is to get data in list of dictionary format.
And the apt solution is this and that too without using django ORM
def fun(request):
from django.db import connections
import json
from psycopg2.extras import RealDictCursor
con = connections['default']
con.ensure_connection()
cursor= con.connection.cursor(cursor_factory=RealDictCursor)
cursor.execute("select * from Customer")
columns=cursor.fetchall()
columns=json.dumps(columns)
output:
[{...},{...},{......}]

Categories

Resources