在python中创建数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17079074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating database in python
提问by chom
I have installed mysql for python and running python from command line. I am getting syntax error while creating a database.
我已经为 python 安装了 mysql 并从命令行运行 python。创建数据库时出现语法错误。
>>> import MySQLdb
>>> CREATE DATABASE chom;
File "<stdin>", line 1
CREATE DATABASE chom;
^
SyntaxError: invalid syntax
回答by Burhan Khalid
CREATE DATABASE chom;this should be run from the MySQL command line client, not from the Python shell.
CREATE DATABASE chom;这应该从 MySQL 命令行客户端运行,而不是从 Python shell 运行。
So, first type mysql -u yourusername -pfrom your command line. It will ask you for a password, type it in. Then you will get a prompt like this mysql>. Here is where you would type that query.
所以,首先mysql -u yourusername -p从你的命令行输入。它会要求你输入密码,输入它。然后你会得到这样的提示mysql>。您可以在此处键入该查询。
Now, if you want to do this through Python, you can, but it will require some more work.
现在,如果您想通过 Python 执行此操作,则可以,但需要做更多工作。
>>> import MySQLdb as db
>>> con = db.connect(user="foo", passwd="secret")
>>> cur = con.cursor()
>>> cur.execute('CREATE DATABASE chom;')
See this guidefor some examples on how to work with Python and MySQL using the standard DB API.
有关如何使用标准 DB API 使用 Python 和 MySQL 的一些示例,请参阅本指南。
回答by htynkn
If you want create a database,you can try:
如果你想创建一个数据库,你可以尝试:
import MySQLdb
db1 = MySQLdb.connect(host="localhost",user="root",passwd="****")
cursor = db1.cursor()
sql = 'CREATE DATABASE chom'
cursor.execute(sql)

