Skip to content

Commit 87a225c

Browse files
committed
add mysql sample
1 parent b001d0c commit 87a225c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

py3/db/do_mysql.py

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

0 commit comments

Comments
 (0)