Newbee - MySQL create database/table

Gerhard Häring gerhard.nospam at bigfoot.de
Sat Sep 15 14:18:47 EDT 2001


On 15 Sep 2001 11:57:13 CET, Danny Kohn <danny.kohn at systematik.se> wrote:
>Hi.
>I wonder if someone could put here or send me a sample Python scrip on how to
>create a database and how to create a table using MySQL with MySQLdb.  I have
>read a lot of documentation but I just cannot figure this one out or find any
>sample script on how to do this.

Well, there's no difference to using the commandline MySQL interface. Here's an example:

#!/usr/bin/env python
import MySQLdb

con = MySQLdb.connect(user= "gerhard", passwd = "gerhard")
cursor = con.cursor()
cursor.execute("create database ghtest")
cursor.execute("use ghtest")
cursor.execute("create table t1 (id int auto_increment primary key,\
                    name varchar(5))")
cursor.execute("insert into t1 values (null, 'A')")
cursor.execute("insert into t1 values (null, 'B')")
cursor.execute("select * from t1")
print cursor.fetchall()
con.close()

The user must have the necessary privileges to create databases, of course. For
testing this script, I did it the hardcore way: as root, use the "mysql"
utility to open an SQL session, then issue:

    grant all privileges on *.* to gerhard at localhost identified by 'gerhard';

That's only a quick hack for a development machine, for a production database
system, such hacks wouldn't be appropriate. Instead, a more fine-grained access
control should be used.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    public key at homepage
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list