简体   繁体   中英

Python 3.2 script to connect to local MySQL database

I am running an Ubuntu Server. I would like for it to have a Python (v3.2) CGI script that would connect, and run a query, to the local MySQL database I have set up. Currently, the only things I found don't support Python 3.2. Please do not suggest switching to an earlier version of Python, because that is not an option for me.

pymysql - Pure Python MySQL client is very good.
It works with Python 3.x, and doesn't have any dependencies.

This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.

Example:

 import pymysql conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql') cur = conn.cursor() cur.execute("SELECT Host,User FROM user") for r in cur: print(r) cur.close() conn.close()

sqlalchemy supports MySQL and all versions of Python 3 . It's nice because you don't have to write SQL; it makes tables look like classes and records look like objects.

BlaXpirit's answer above to use pymysql works great. But one small caveat. The link to pymysql in his comment will take you to https://github.com/petehunt/PyMySQL/ which is for python 2.x. If you are using python 3, you want to download and install pymysql3 (version 3.0.5 as of 5/12/12) from http://pypi.python.org/pypi/PyMySQL3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM