3

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

6
  • The last line of the update says access denied for user. Are you using the correct username/password?
    – vpit3833
    Commented Mar 15, 2011 at 23:48
  • Why don't you have a password, btw? It says "using password: NO".
    – 9000
    Commented Mar 15, 2011 at 23:49
  • @vpit3833,@9000 - Looking at the parameters Mahmoud suggest to pass the connect method, there is no username parameter, i don't know why. I haven't set up a password for MySQL yet so i use username root and password '' and that works fine from MySQL and phpMyAdmin.
    – Babiker
    Commented Mar 15, 2011 at 23:51
  • 1
    OK, a more elaborate signature looks like MySQLdb.connect(host=hostname, user=username, passwd=password, db=database_name). Password being empty is OK as long as you are just learning and mucking around :)
    – vpit3833
    Commented Mar 15, 2011 at 23:55
  • @vpit3833, I'll update my answer Commented Mar 16, 2011 at 0:23

1 Answer 1

2

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.