Python-数据库操作-pymysql

来源:互联网 发布:魔鬼积木知乎 编辑:程序博客网 时间:2024/04/29 12:04

pymsql是Python中操作MySQL的模块,和之前使用的MySQLdb模块基本功能一致;
首先安装pymysql,可使用pip来安装,很方便,不过前提是按照pip以及有外网。
在cmd环境下执行:

pip install pymysql

pymysql的基本操作如下:

#!/usr/bin/env python#   --coding = utf-8#   Author Allen Leeimport pymysql#创建链接对象conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='Allen')#创建游标cursor = conn.cursor()#执行sql,更新单条数据,并返回受影响行数effect_row = cursor.execute("update hosts set host = '1.1.1.2'")#插入多条,并返回受影响的函数effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)])#获取最新自增IDnew_id = cursor.lastrowid#查询数据cursor.execute("select * from hosts")#获取一行row_1 = cursor.fetchone()#获取多(3)行row_2 = cursor.fetchmany(3)#获取所有row_3 = cursor.fetchall()#重设游标类型为字典类型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#提交,保存新建或修改的数据conn.commit()#关闭游标cursor.close()#关闭连接conn.close()
0 0
原创粉丝点击