Kuidas ühendada MySQL-andmebaasiga, kasutades python-programmi?
Siin on üks võimalus seda teha, kasutades MySQLdb, mis toetab ainult Python 2:
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()
Proovige kasutada MySQLdb. MySQLdb toetab ainult Python 2.
Siin on lehekülg, kuidas seda teha: http://www.kitebird.com/articles/pydbapi.html.
Leheküljelt:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
MySQLdb on lihtne viis. Saate SQL päringuid läbi ühenduse täita. Periood.
Minu eelistatud viis, mis on samuti pütooniline, on selle asemel kasutada võimsat SQLAlchemy. Siin on päringutega seotud õpetus ja siin on SQLALchemy ORM-võimaluste õpetus.