creating a new database with mysqldb

Jesse Hager wrffruntre at tznvy.pbz.ROT13
Wed May 17 21:25:32 EDT 2006


John Salerno wrote:
> Since the connect method of mysqldb requires a database name, it seems
> like you can't use it without having a database already created. So is
> there a way to connect to your mysql server (without a specified
> database) in order to create a new database (i.e., the CREATE DATABASE
> query)?
> 
> Thanks.

In every MySQL library I have ever seen, the database parameter is
optional.  You may either omit it or pass an empty string.  It is just a
shortcut so the application does not need to send a "USE" command to
select the active database.

>>>import MySQLdb
>>>db = MySQLdb.connect("host","username","password")
>>>c = db.cursor()

To get the currently selected database:

>>>c.execute("SELECT DATABASE()")
1L
>>>c.fetchall()
((None,),)
  ^^^
None (NULL) indicates no currently selected database.

To set the default database:

>>>c.execute("USE mysql")
0L

Getting the database again:

>>>c.execute("SELECT DATABASE()")
1L
>>>c.fetchall()
(('mysql',),)
  ^^^
A string indicates that a database is currently selected.

Hope this helps.

-- 
Jesse Hager
email = "wrffruntre at tznvy.pbz".decode("rot13")



More information about the Python-list mailing list