Tuesday, October 9, 2012

how to use python mysqldb to create database?



Scenario:
how to use python mysqldb to create database?


Answer:
Just connect without the parameter 'db' and use the SQL statement to create the database.

http://forums.mysql.com/read.php?50,235668,236194#msg-236194



You just need to connect without the parameter "db". 
Then you can execute the "create" query. 
You can olso use the query "USE db_name" to say what database you are going to use. 

This code works to me: 

db=MySQLdb.connect(user='root') 
c=db.cursor() 
c.execute('CREATE DATABASE pippo') 


This is the link with sql manual: 
http://dev.mysql.com/doc/refman/5.0/en/sql-syntax.html 
The "USE" statement is in "SQL Utility Statements"

Original question:
http://forums.mysql.com/read.php?50,235668,235668

Hi, 

I just want to ask something from this code. 

import MySQLdb 
db = MySQLdb.connect(host="localhost", user="joe", passwd="secret",db="db56a") 
cursor = db.cursor() 
cursor.execute("SELECT * FROM animals") 

In the code, I first Import the MySQLdb. Afterwhich I made a connection. But in order for me to make a connection, I must first have a database named db56a. Or else it will tell that db56a doesn't exist. Is there anyway that I can create a database before making a connection? Because what I need is a user to input the name of the database he/she wants to make. Then with the name, I could create already the database. 

so my query will be like: 
cursor.execute("create database %s" %database_name) 

will it be possible? 

Thanks, 
Pat







No comments:

Post a Comment