I have to retrieve data from a database. Right now i am using the following code:
import mysql.connector
connection = mysql.connector.connect(user, password, host, database)
cursor = connection.cursor()
cursor.execute(*Query*)
data = cursor.fetchall()
name = data[0][0]
surname = data[0][1]
I would need to access the data by field name instead of raw indexes. For instance something like that
name = data[0]['name']
surname = data[0]['surname']
Thanks
One option is to use MySQLdb. Then you can change:
cursor = connection.cursor()
To:
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
and access the values by field names instead indexes.
According to mysql-connector-python documentation, there are two ways to achieve this.
Manually:
cursor = cnx.cursor()
cursor.execute(...)
row = dict(zip(cursor.column_names, cursor.fetchone()))
With MySQLCursorDict class:
cursor = cnx.cursor(dictionary=True)
Related
How can we fetch details of particular row from mysql database using variable in python?
I want to print the details of particular row using variable from my database and I think I should use something like this:
data = cur.execute("SELECT * FROM loginproject.Pro WHERE Username = '%s';"% rob)
But this is showing only the index value, not the data. Please help me out.
after executing the query using cur.execute(query), you need to call fetchall function for getting data from cursor e.g.:
data = cur.fetchall()
Something like this?
cur = db.cursor()
cur.execute("SELECT * FROM loginproject.Pro WHERE Username = '%s';"% rob)
result = cur.fetchall()
for row in result:
print(row[0])
https://github.com/prosaigon/Python-Connector-Mysql
python3.6
library: pip install mysqlclient
use cursor.fetchall and cursor.description is your case
cursor.fetchall():
This will provide you all the rows fetched in a tuple format.
cursor.description:
This will provide you the list of columns in the query
And the one will go like :
cur.execute("SELECT * FROM loginproject.Pro WHERE Username = '%s';"% rob)
descriptor = cur.description
result = cur.fetchall()
I am trying to get Information from my database, and print it, but unfortunately, Instead of Printing the Information from the Table, it just Prints 0 or 1.
Why does it do this?
Can someone please help me?
sql = ("SELECT code FROM testing WHERE email = ((%s))")
sql2 = a.execute(sql, (fullemail))
sqlusername = ("SELECT username FROM testing123 WHERE code = ((%s))")
username = a.execute(sqlusername, (sql2))
print("Test3")
print(username)
Thank you.
The execute() method just returns the number of impacted rows.
You must use .fetchall() or equivalent (e.g. .fetchone()...) DBAPI methods to get a resultset.
Also, using parentheses alone around a single value: (fullemail) will not be recognized as a tuple, you need to explicitly add a comma so Python will recognize this as a tuple: (fullemail, )
sql = ("SELECT code FROM testing WHERE email = %s")
a.execute(sql, (fullemail, ))
sql2 = a.fetchall()
print(sql2)
sqlusername = ("SELECT username FROM testing123 WHERE code = %s")
a.execute(sqlusername, (sql2[0][0], ))
username = a.fetchall()
print("Test3")
print(username)
Depending on which library you are using:
MySQLdb (python 2.7)
mysqlclient (MySQLdb for python3)
PyMySQL (pure Python)
You can also use a DictCursor to get your result set rows as dict instead of list. Usage is like:
from pymysql.cursors import DictCursor
import pymysql
db = pymysql.connect(host="", user="", passwd="", cursorclass=DictCursor)
with db.cursor() as cur:
cur.execute("SELECT ...")
results = cur.fetchall()
This will give you a list of dictionaries instead of a list of lists.
I'm working with python and using pymysql library and i want to write a query that insert an array in a line where a column has some special value.
For example insert 'hi' into a column where user_id is 22
for that query i write this code
from pymysql import *
chat_id = 22
user_first_name = "hi"
db = connect(host="localhost", port=3306, user="root", passwd="",
db='support',charset='utf8')
cursor = db.cursor()
cursor.execute("""INSERT INTO users user_firstname VALUE %s WHERE user_id is
%s""",(user_first_name, chat_id))
db.commit()
how should i write this query in correct form?
If I'm undertanding, correctly, rather than an INSERT INTO, it seems you need an UPDATE:
cursor.execute("""UPDATE users SET user_firstname='%s' WHERE user_id=%s""",(user_first_name, chat_id))
Francisco is right though. If you have a user_id already, then an UPDATE should be used to change the value of and existing record. The INSERT command, creates a new record.
In Python mysqldb I could declare a cursor as a dictionary cursor like this:
cursor = db.cursor(MySQLdb.cursors.DictCursor)
This would enable me to reference columns in the cursor loop by name like this:
for row in cursor: # Using the cursor as iterator
city = row["city"]
state = row["state"]
Is it possible to create a dictionary cursor using this MySQL connector?
http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
Their example only returns a tuple.
I imagine the creators of MySQL would eventually do this for us?
According to this article it is available by passing in 'dictionary=True' to the cursor constructor:
http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
so I tried:
cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(dictionary=True)
and got:
TypeError: cursor() got an unexpected keyword argument 'dictionary'
and I tried:
cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(named_tuple=True)
and got:
TypeError: cursor() got an unexpected keyword argument 'named_tuple'
and I tried this one too: cursor = MySQLCursorDict(cnx)
but to no avail. Clearly I'm on the wrong version here and I suspect we just have to be patient as the document at http://downloads.mysql.com/docs/connector-python-relnotes-en.a4.pdf suggests these new features are in alpha phase at point of writing.
A possible solution involves subclassing the MySQLCursor class like this:
class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
def _row_to_python(self, rowdata, desc=None):
row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
if row:
return dict(zip(self.column_names, row))
return None
db = mysql.connector.connect(user='root', database='test')
cursor = db.cursor(cursor_class=MySQLCursorDict)
Now the _row_to_python() method returns a dictionary instead of a tuple.
I found this on the mysql forum, and I believe it was posted by the mysql developers themselves. I hope they add it to the mysql connector package some day.
I tested this and it does work.
UPDATE: As mentioned below by Karl M.W... this subclass is no longer needed in v2 of the mysql.connector. The mysql.connector has been updated and now you can use the following option to enable a dictionary cursor.
cursor = db.cursor(dictionary=True)
This example works:
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
print("Countries in Europe:")
for row in cursor:
print("* {Name}".format(Name=row['Name']
Keep in mind that in this example, 'Name' is specific to the column name of the database being referenced.
Also, if you want to use stored procedures, do this instead:
cursor.callproc(stored_procedure_name, args)
result = []
for recordset in cursor.stored_results():
for row in recordset:
result.append(dict(zip(recordset.column_names,row)))
where stored_procedure_name is the name of the stored procedure to use and args is the list of arguments for that stored procedure (leave this field empty like [] if no arguments to pass in).
This is an example from the MySQL documentation found here: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
Using Python 3.6.2 and MySQLdb version 1.3.10, I got this to work with:
import MySQLdb
import MySQLdb.cursors
...
conn = MySQLdb.connect(host='...',
<connection info>,
cursorclass=MySQLdb.cursors.DictCursor)
try:
with conn.cursor() as cursor:
query = '<SQL>'
data = cursor.fetchall()
for record in data:
... record['<field name>'] ...
finally:
conn.close()
I'm using PyCharm, and simply dug into the MySQLdb modules connections.py and cursors.py.
I had the same problem with the default cursor returning tuples with no column names.
The answer is here:
Getting error while using MySQLdb.cursors.DictCursor in MYSQL_CURSORCLASS
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
I have an access table that I am trying to add fields programmatically using Python. It is not a personal geodatabase. Just a standard Access database with some tables in it.
I have been able to access the table and get the list of field names and data types.
How do I add a new field and assign the data type to this Access table using Python.
Thanks!
SRP
Using the pyodbc module:
import pyodbc
MDB = 'c:/path/to/my.mdb'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = 'my_password'
conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))
c = conn.cursor()
c.execute("ALTER TABLE my_table ADD COLUMN my_column INTEGER;")
conn.commit()
c.close()
conn.close()
Edit:
Using win32com.client...
import win32com.client
conn = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/path/to/my.mdb;'
conn.Open(DSN)
conn.Execute("ALTER TABLE my_table ADD COLUMN my_column INTEGER;")
conn.Close()