在 python 中创建 MySQL 数据库

Create a MySQL database in 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 数据库来使用?

正在 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') 到 select 即 table 和 c.execute('create table statement')create a table

使用 pip 安装 mysql 连接器,

sudo pip install mysql-connector-python

创建数据库 gtec 和 table 学生的示例代码,

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()