forked from michaelliao/learn-python3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_mysql.py
More file actions
executable file
·31 lines (25 loc) · 867 Bytes
/
do_mysql.py
File metadata and controls
executable file
·31 lines (25 loc) · 867 Bytes
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
#!/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='password', 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'))
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()