在python中创建一个MySQL数据库

时间:2015-11-17 22:35:18

标签: python mysql mysql-python

我期待从Python中创建一个MySQL数据库。我可以找到有关如何连接到现有数据库的说明,但不能找到如何初始化新数据库的说明。

例如,当我运行

行时
import MySQLdb
db = MySQLdb.connect(host="localhost", user="john", passwd="megajonhy", db="jonhydb")  (presumably because connecting will not create a database if it doesn't already exist, as i had hoped)

关于How do I connect to a MySQL Database in Python?的第一行说明,我收到错误_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

如何初始化新的MySQL数据库以使用?

2 个答案:

答案 0 :(得分:8)

用Python创建数据库。

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="password")

c = db.cursor()
c.execute('create database if not exists pythontest')

db.close()

使用CREATE DATABASE MySQL语句。

这不常见,因为每次运行脚本时都会尝试创建该数据库。

注意 - 然后,您可以使用db.select_db('pythontest')选择该表,并c.execute('create table statement')create a table

答案 1 :(得分:0)

使用pip安装mysql连接器,

sudo pip install mysql-connector-python

用于创建数据库gtec和table student的示例代码,

import mysql.connector    
cnx = mysql.connector.connect(user='root', password='1234',
                              host='localhost',
                              database='gtec')

try:
   cursor = cnx.cursor()
   cursor.execute("select * from student")
   result = cursor.fetchall()
   print result
finally:
    cnx.close()
相关问题