python数据库画表
时间: 2023-07-25 08:31:01 浏览: 55
在 Python 中,可以使用各种数据库管理系统来创建和管理数据库表。其中最常用的是使用 SQL 语言来操作关系型数据库,如 MySQL、PostgreSQL、SQLite 等。
以下是使用 Python 操作 MySQL 数据库的示例代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
# 查询数据
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
这段代码使用了 Python 的 mysql.connector 模块来连接 MySQL 数据库,并创建了一个名为 "customers" 的表,然后插入了一条数据,最后查询了所有数据并输出。你可以根据自己的需求来修改表结构和操作数据。