python pymysql 创建 一个带有id的表,举个例子,并插入一条数据
时间: 2023-11-28 15:48:54 浏览: 32
好的,以下是创建一个带有id的表并插入一条数据的示例代码:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='test_db')
cursor = db.cursor()
# 创建表
create_table_sql = '''
CREATE TABLE IF NOT EXISTS `example` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
'''
cursor.execute(create_table_sql)
# 插入数据
insert_data_sql = '''
INSERT INTO `example` (`name`) VALUES ('John');
'''
cursor.execute(insert_data_sql)
db.commit()
# 关闭连接
cursor.close()
db.close()
```
以上代码创建了一个名为 `example` 的表,该表包含 `id` 和 `name` 两个字段,其中 `id` 是自增长的主键。然后,插入了一条名为 `John` 的数据。需要注意的是,执行插入操作后需要调用 `commit()` 方法提交事务,否则数据不会真正写入数据库。