With this simple guide will be introduced how to connect to a mysql database with MySQLdb library. First make sure you have installed on your system python (in the case of windows, at the time of writing you will need version 2.5). Now MySQdb download the library, if you use linux just use the package manager, if you use the windows can be found here while if you use a mac you have to do anything. To use the MySQL database to be installed in vostra macchina.
Definiamo una tabella semplicissima per l'esempio, dentro il database test inserendo nel da riga di comando di MySql le seguenti:
mysql> create database test;
mysql> use test;
mysql> create table persona (id int not null auto_increment primary key,nome varchar(50) not null,cognome varchar(50) not null);
bene ora abbiamo creato la nostra tabella nel database test.
Apriamo il nostro editor preferito e scriviamo il nostro script che andrĂ ad inserire un record nel database e leggerĂ i dati dentro la tabella persona:
import MySQLdb
#Creiamo la connessione
db = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "tests") # We get the cursor
db.cursor c = () # perform the insert
c.execute ("INSERT INTO person (name, surname) VALUES (\\ "Richard \\" \\ "Degan \\") ") # execute the select
c.execute (" SELECT * FROM person ") # We get all tuples
c.fetchall result = () # prints
for a video res in result:
print "NAME:% s NAME:% s \\ n"% (res [1], res [2])
Save the file with any name and extension. py. Open a shell and move to the directory where we saved the newly created file and type: python
nome_file.py
we get an output like this:
NAME: Richard SURNAME: Degan
The way to connect is really simple and useful thing that python being interpreted is convenient to make changes fast and easy!
0 comments:
Post a Comment