python实战第一天-pymysql模块并练习

时间:2022-01-20 22:33:08
操作系统

Ubuntu 15.10

IDE & editor

JetBrains PyCharm 5.0.2

ipython3

Python版本

python-3.4.3

安装pymysql模块

jim@jim-virtual-machine:~$ pip3 install PyMySQL
Collecting PyMySQL
Downloading PyMySQL-0.7.2-py2.py3-none-any.whl (76kB)
100% |████████████████████████████████| 77kB 18kB/s
Installing collected packages: PyMySQL

mysql -u root -p

创建数据库
mysql> create database testdb;
Query OK, 1 row affected (0.10 sec) 授权用户访问
mysql> grant all on testdb.* to 'jim'@'127.0.0.1' identified by '123456';
Query OK, 0 rows affected (0.25 sec) mysql> grant all on testdb.* to 'jim'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.25 sec) 刷新
mysql > flush privileges;
Query OK, 0 rows affected (0.11 sec)
导入pymysql模块
import pymysql
jim@jim-virtual-machine:~$ pip3 list #显示已安装的模块
上面的忽略
PyMySQL (0.7.2)
下面的忽略
conn = pymysql.connect(host='127.0.0.1',port=3306,user='jim',password='123456') #创建连接过程

cur = conn.cursor() 创建游标

cur.execute("""CREATE TABLE tbl_category(
....: id VARCHAR (1) NOT NULL PRIMARY KEY,
....: category VARCHAR (10))""")

####插入一个表、

cur.execute("""CREATE TABLE tbl_category(
....: id VARCHAR (1) NOT NULL PRIMARY KEY,
....: category VARCHAR (10))""")

#插入数据

cur.execute('''INSERT INTO tbl_category VALUES ('1','aa')''')
cur.execute('''INSERT INTO tbl_category VALUES ('2','bb')''')

#提交数据

conn.commit()

读取数据

cur.execute("select * from tbl_category")
data = cur.fetchall() print(data)
(('1', 'aa'), ('2', '??'), ('3', 'bb'), ('4', 'dd'), ('5', 'aaa'))

判断如果data有值则输出结果

if data:
.....: for record in data:
.....: print(record)
.....:
('1', 'aa')
('2', '??')
('3', 'bb')
('4', 'dd')
('5', 'aaa')