Python数据库编程

本文主要介绍python数据库编程相关知识。

1.安装MySQL和MySQL驱动

1
2
# yum install gcc python-devel mysql-devel zlib-devel openssl-devel
# pip install MySQL-python

2.数据库连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/pyton

import MySQLdb
conn = MySQLdb.connect(user='root',passwd='',host='localhost') //连接数据库
cur = conn.curson() //创建连接游标
conn.select_db('test') //选择数据库
cur.execute('create table info(id tinyint)') //执行sql语句
cur.execute('insert into info values(1),(2),(3)') //执行sql语句
cur.execute('select * from info') //执行sql语句
cur.fetchone() //执行sql语句
cur.scroll(0,'absolute')
cur.fetchmany(3)
cur.fetchmany(cur.execute('select * from info'))
cur.close()
conn.close()
---------------- The End ----------------