Python与数据库交互的基本操作步骤:
1、连接数据库
2、建立游标
3、执行sql语句
4、关闭游标、关闭数据库连接
1 import pymysql,redis 2 def OpertionMysql(host,user,passwd,db,sql,port=3306,charset='utf8'): 3 conn = pymysql.connect( 4 host=host, # 连接的数据库服务器的主机名 5 user=user, # 登录数据库的用户名 6 passwd=passwd, # 登录数据库的密码 7 port=port, # 端口号,MySQL 默认是3306 8 db=db, # 要使用的数据库名 9 charset=charset # 字符编码 10 )#建立连接 11 cur = conn.cursor(cursor=pymysql.cursors.DictCursor)# 建立游标 指针对象 12 cur.execute(sql) # 执行sql ,执行单条sql语句,接手的参数为sql语句本身和使用的参数列表 13 if sql.startswith('select'):#判断语句,如果是查询语句 14 res = cur.fetchone() # 接收返回值,接收一条返回结果 15 # res = cur.fetchall() # 接收全部的返回结果。返回结果集中的全部数据,结果为一个tuple的列表 16 else: # 如果是增删改语句 17 conn.commit() # 提交新增和修改 18 res = 666 19 cur.close() # 关闭游标 20 conn.close() # 关闭数据库连接 21 return res 22 23 if __name__ == '__main__': 24 sql1 = 'insert into alina(id,username,password) value(98,"alina","123456")' # 新增 25 sql2 = 'select * from alina limit 3;' # 查询 26 sql3 = 'delete from alina where id = 1;' # 删除 27 sql4 = 'update alina set name = "hello" where id = 3;' # 修改 28 s = OpertionMysql( 29 host='172.16.1.42',user='root',passwd='123456',db='alina', 30 sql = sql1 31 )
scroll(self, value, mode='relative'):移动指针到某一行。如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条。