-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqltest.py
32 lines (26 loc) · 942 Bytes
/
mysqltest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########## prepare ##########
# install mysql-connector-python:
# pip3 install mysql-connector-python --allow-external mysql-connector-python
import mysql.connector
# change root password to yours:
conn = mysql.connector.connect(user='root', password='123456', database='test')
cursor = conn.cursor()
# 创建user表:
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('insert into user (id, name) values (%s, %s)', ('1', 'Michael'))
cursor.execute('insert into user (id, name) values (%s, %s)', ('2', 'Steve'))
print('rowcount =', cursor.rowcount)
# 提交事务:
conn.commit()
cursor.close()
# 运行查询:
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', ('1',))
values = cursor.fetchall()
print(values)
# 关闭Cursor和Connection:
cursor.close()
conn.close()