Python 创建数据库
Python基础 2022-06-06 12:57:54小码哥的IT人生shichen
Python 创建数据库
创建数据库
如需在 MySQL 中创建数据库,请使用 "CREATE DATABASE" 语句:
示例代码:
创建名为 "mydatabase" 的数据库:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
#If this page is executed with no error, you have successfully created a database.
如果执行上面的代码没有错误,则您已成功创建数据库。
检查数据库是否存在
您可以通过使用 "SHOW DATABASES" 语句列出系统中的所有数据库,检查数据库是否存在:
示例代码:
返回系统中的数据库列表:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
或者您可以在建立连接时尝试访问数据库:
示例代码:
尝试连接数据库 "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
#If this page is executed with no error, the database "mydatabase" exists in your system
如果数据库不存在,会收到错误。