Database
MySql
Python
Python
Børre Stenseth

Databaser

Hva

Dette materialet er basert på MySQL. Lenkene nderst på siden gir instruksjoner om hvordan laste ned og installere drivere for MySQL.

Eksempel Python3

Et basis eksempel som laster ned data fra en database over viner. Eksempelet er skrevet i Python3. Av sikkerhetsmessige årsaker vil du ikkekunne bruke denne koden direkte mot den oppgitte databasen, men du kan lett opprette din egen MySQL-base, f.eks. på localhost, og ekseprimentere med koden.

"""
Testing database access
Database table:
    create table wines(
        vin_id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100),
        catalog CHAR(10),
        type CHAR(10),
        country VARCHAR(20),
        dice TINYINT,
        volume INT,
        price CHAR(10),
        description TEXT
    );
"""
import mysql.connector
from mysql.connector import errorcode
config = {
  'user': 'student',
  'password': 'student',
  'host': 'itstud.hiof.no',
  'database': 'vin',
  'raise_on_warnings': True,
}
def connectAndExecute(query):
    try:
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor()
        cursor.execute(query)
        return cursor.fetchall()
    except mysql.connector.Error as err:
        print(err)
        return None
    else:
        cnx.close()
        

if __name__=="__main__":       
    SQL_SELECT_WINES="""SELECT name,dice FROM wines 
    WHERE country='%s' AND type='%s';"""
    
    results=connectAndExecute(SQL_SELECT_WINES%('Portugal','white'))
    if results!=None:
        print (str(len(results))+' hvite viner fra Portugal')
        print ('------------------------')
        for ix in range(0,len(results)):
            record=results[ix]
            print (str(record[1])+' : '+record[0])

Som gir følgende resultat:

_resultat

Eksempel Python2

Samme oppgave løst i Python2

"""
Testing database access
"""
import MySQLdb
#----------------------------------
# connect and execute a sql-request
def connectAndExecute(sql):
    myBase=None
    try:
        myBase=MySQLdb.connect(host='itstud.hiof.no',
                               user='student',
                               passwd='student',
                               db='vin')
        myTab=myBase.cursor()
        myTab.execute(sql)
        myBase.commit()
        myBase.close()
        return myTab.fetchall()
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        if myBase!=None:
            myBase.close()
        return None
if __name__=="__main__":       
    SQL_SELECT_WINES="""SELECT name,dice FROM wines 
    WHERE country='%s' AND type='%s';"""
    
    results=connectAndExecute(SQL_SELECT_WINES%('Portugal','white'))
    if results!=None:
        print str(len(results))+' hvite viner fra Portugal'
        print '------------------------'
        for ix in range(0,len(results)):
            record=results[ix]
            print str(record[1])+' : '+record[0]
        
[1] [2] [3] [4]
Referanser
  1. Download Connector/Python MySQL dev.mysql.com/downloads/connector/python/ 14-03-2014
  1. Connecting to MySQL Using Connector/Python MySQL dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html 14-03-2014
  1. Unofficial Windows Binaries for Python Extension Packages www.lfd.uci.edu/~gohlke/pythonlibs/ 01-03-2014
  1. MySQL, kort om SQLzoo.net sqlzoo.net/ 14-03-2014