pymsql
谨为作者笔记用
pymsql是python操作数据库的一个包,我们可以使用它对数据库进行操作。
引入pymysql
- 首先pip install pymysql,然后在文件中引入
连接数据库
1
| db=pymsql.connect('localhost', 'user', 'password', charset='utf8')
|
- 依次是服务器地址,本地的话则为localhost,用户名,密码。。。
创建游标,可以把它想象成操作数据的一个对象
执行对数据库的操作
- sql command 便是平常我们操作数据库时使用的命令,这里没有任何差别
1 2
| cursor.execute('sql command') cursor.execute('select * from tablename')
|
提交到数据库
执行错误的话
最后,关闭连接
1 2
| cursor.close() db.close()
|
- 建议从操作到关闭,都放在try catch代码块中
- 如:
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #!/usr/bin/python # -*- coding: utf-8 -*-
#加载pymysql模块,借此模块python才能对数据库进行操作 import pymysql
#创建连接 db = pymysql.connect('localhost', 'user', 'password', 'databaseName', charset='utf8')
#创建游标,可以想象成一个对数据库操作的对象 cursor = db.cursor()
#显示当前所有的数据库 cursor.execute('show databases;') print('当前存在的所有数据库...') print('=' * 20) for item in cursor.fetchall(): print(item[0]) print('=' * 20)
#执行sql操作命令 while True: #输入需要执行的命令 sqlCmdEnter = input('请输入需要执行的sql操作命令(请在末尾加上分号):') try: #执行 cursor.execute(sqlCmdEnter) #提交到数据库,不然无法保存新建或修改的数据 db.commit() #获取查询的所有记录 for item in cursor.fetchall(): print(item) print('执行成功!') except Exception as e: print('执行错误!') db.rollback() finally: #是否继续操作 isContinue = input('是否继续执行(y/n):') if isContinue == 'n' or isContinue == 'no': cursor.close() db.close() #关闭连接 print('关闭连接!\n退出程序!') break
|