1 安装相关模块PyMySQL
PyMySQL是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
1 pip install PyMySQL
安装完毕后,在IDLE中运行“import pymysql”,如果没有出错,则安装成功。
注意:我之前不知道Python2和Python3使用的MySQL模块不同,所以一直安装“mysqldb”,后来发现不同,了之。
参考资料:http://www.runoob.com/python3/python3-mysql.html
2 查找数据库数据
1 import pymysql 2 3 # 打开数据库连接("主机","账号","密码","数据库名","编码方式") 4 db = pymysql.connect("localhost","root","root","textsim",charset="utf8") 5 6 # 使用cursor()方法获取操作游标 7 cursor = db.cursor() 8 9 # SQL 查询语句 10 sql = "SELECT * FROM user" 11 try: 12 # 执行SQL语句 13 cursor.execute(sql) 14 # 获取所有记录元组 15 results = cursor.fetchall() 16 # 获取每条数据的元组 17 for row in results: 18 print(row) 19 except: 20 print ("Error: unable to fetch data") 21 22 # 关闭数据库连接 23 db.close()
3 增加数据库数据
1 import pymysql 2 3 # 打开数据库连接("主机","账号","密码","数据库名","编码方式") 4 db = pymysql.connect("localhost","root","root","textsim",charset="utf8") 5 6 # 使用cursor()方法获取操作游标 7 cursor = db.cursor() 8 9 # SQL 插入语句 10 sql = "INSERT INTO user VALUES ('是的哈哈', 'Mohan', '882736@qq.com', '2')" 11 try: 12 # 执行SQL语句 13 cursor.execute(sql) 14 # 提交到数据库执行 15 db.commit() 16 # 写入成功 17 print("Insert data successfully!") 18 except: 19 # 如果发生错误则回滚 20 db.rollback() 21 22 # 关闭数据库连接 23 db.close()
注意:更新、删除操作与增加类似,只需要更改sql语句即可。
参考:https://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html#d1