用python创建MySQL数据库

2024-03-29 01:51:19 发布

您现在位置: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数据库?在


Tags: toimport数据库localhosthostdbconnectmysql
1条回答
网友
1楼 · 发布于 2024-03-29 01:51:19

用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 DATABASEMySQL语句。在

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

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

相关问题 更多 >