Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the process for using MySQL from Python in Windows?

I come from a PHP background where MySQL easily works from PHP, and don't the process for getting MySQL to work from Python. From all the research i did and reading of similar yet non-exact questions, it seems to me that there are different ways to achieve this, which makes it even harder for me to wrap my head around. So far I have MySQL-python-1.2.3 installed for python 2.7.1 in Windows XP 32Bit. Can anyone give me an overview of what is necessary to get MySQL working from Python in Windows, or even what is next after my steps all the way to fetching a table row? Thanks in advance.


UPDATE:

@Mahmoud, using your suggestion i have triggered the following: enter image description here

like image 390
Babiker Avatar asked Jul 26 '26 01:07

Babiker


1 Answers

If you just want to use the DBAPI, then here's a simple snippet explaining how to issue a SELECT query.

import MySQLdb
db = MySQLdb.connect(host="host", user="username", passwd="your-pass", db="the-db-name")

To perform a query, you first need a cursor, and then you can execute queries on it:

cursor = db.cursor()
max_age = 42
cursor.execute("""SELECT name FROM employees WHERE age < %s""", (max_age,))
print cursor.fetchone()

However, you most likely want to use an ORM, I recommend SQLAlchemy. It essentially trivializes database interaction by providing a super-powerful abstraction layer.

like image 106
Mahmoud Abdelkader Avatar answered Jul 27 '26 14:07

Mahmoud Abdelkader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!