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大小,获取相应的数量