python3 使用 pymysql 对 MySQL 进行操作, python2 则使用 mysqldb
1. 安装 pymysql 的命令:
pip install pymsql
如果因网络问题下载失败, 则使用如下命令指定国内源下载
pip install pymysql -i http://pypi.douban.com/simple/ --trusted-host http://pypi.douban.com/
2. 数据库连接:
- import pymsql
- # 创建连接
- conn=pymysql.connect(host="localhost",port=3306,user="testuser",passwd="test123",db="TESTDB" )
- # 创建游标对象:
- cur
- = conn
- .cursor()
- # 关闭游标
- cur.close()
- # 关闭连接
- conn.close()
3. 查询:
- sql="select * from info"
- cur.execute(sql)
- # 返回查询的一条记录
- data=cur.fetchone()
- # 返回查询的所有结果
- data=cur.fetchall()
4. 插入:
- sql2 = "insert into info(NAME,address ) VALUES(%s,%s)" # sql 语句,%s 是占位符 (%s 是唯一的, 不论什么数据类型都使用 %s) 用来防止 sql 注入
- params = ('eric', 'wuhan') # 参数
- reCount = cur.execute(sql2, params)
- # 批量插入
- li = [('a1', 'b1'), ('a2', 'b2')]
- sql3 = 'insert into info(NAME ,address) VALUES (%s,%s)'
- reCount = cur.executemany(sql3, li)
- conn.commit() # 提交, 执行多条命令只需要 commit 一次就行了
5. 更改数据
- sql3="update tfundinfo set c_state='1'where c_fundcode="%s" "%(m)
- cur.execute(sql3)
- conn.commit()
6. 删除数据
- sql=
- "DELETE FROM EMPLOYEE WHERE AGE>'%d'
- " % (20)
- cur.execute(sql)
- conn.commit()
7. 查询返回 dict 类型数据
- # 在创建游标时, 指定返回结果为 dict
- cur=conn.cursor(cursor=pymysql.cursors.DictCursor)
- sql="select * from info"
- cur.execute(sql)
- # 返回查询的一条记录
- data=cur.fetchone()
- # 返回查询的所有结果
- data=cur.fetchall()
来源: http://www.bubuko.com/infodetail-2819591.html