Pages

Wednesday, September 4, 2013

Access Database - Python

Contoh: import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","user","pass","db_name" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM person"

try:
    # Execute the SQL command
    cursor.execute(sql)
    # Fetch all the rows in a list of lists.
    results = cursor.fetchall()
    for row in results:
        p_alias = row[1]
        p_image = row[3]
        # Now print fetched result
        print "p_alias=%s,p_image=%s" % \
              (p_alias, p_image)
except:
    print "Error: unable to fecth data"

# disconnect from server
db.close()

No comments:

Post a Comment