Python数据库常用的操作

Python数据库操作

Ubuntu操作系统下可以常用软件库来安装

sudo apt-get install build-esseatial python-devlibmysqlclient-dev

sudo apt-get install python-MySQLdb

或者使用pip install mysql-python

安装后,在python交互模式下:

import MySQLdb

#!/usr/bin/env python
#coding:utf-8
import MySQLdb
conn = MySQLdb.connect(host="localhost",user="root",passwd="root1234",db="new_db",port=3306,charset="utf8")//注意passwd以及charset添加解决乱码问题
cur = conn.cursor()  #获得游标对象
cur.execute("insert into users(username,password,email) values(%s,%s,%s)",("python","123456","python#163.com"))//executemany
conn.commit()  //将数据进行提交
cur = conn.cursor()
value = cur.execute("select * from users")   #返回符合要求的数量
# print value
lines = cur.fetchall()
for line in lines:
    print line     //全部打印出来
 

将读取到的数据改为字典形式:

cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("select * from users")
print cur.fetchall()
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("select * from users")
print cur.fetchall()
cur.scroll(-3)   //改变游标的指向
print cur.fetchone()
print cur.fetchmany(2)  //指定size大小,获取相应的数量

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值