1 导入MySQLdb 库
import MySQLdb
2 连接数据库
conn = MySQLdb.connect(host="localhost" , user = "root" , passwd = "123456",db = "path_restore" , charset= "utf8")
connect()方法用来和数据库连接,返回连接对象。
connect中常用的参数有:
- host , 数据库主机名,默认本地
- user , 数据库用户名,默认root
- passwd , 数据库登录密码
- db , 要连接的数据库
- charset , 数据库编码
3 执行sql语句和接收返回值
cursor=conn.cursor()
n=cursor.execute(sql,param)
1 先使用连接对象获得一个指针对象
2再用指针对象提供的方法执行和接收返回值
cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self,size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value,
mode=’relative’):移动指针到某一行.如果mode=’relative’,则表示从当前所在行移动value条,如果mode=’absolute’,则表示从结果集的第一行移动value条.
4 关闭数据库连接
cursor.close()
conn.close()
分别关闭指针对象和连接对象
5 demo
# -*- coding: utf-8 -*-
# mysqldb
import MySQLdb
conn = MySQLdb.connect(host="localhost" , user = "root" , passwd = "123456",db = "path_restore" , charset= "utf8")
cursor = conn.cursor()
sql = "select enter, cost , vclass from virtual_edge_data where metadata_id = '%d' " % (1)
cursor.execute(sql )
for row in cursor.fetchall():
print row
for r in row :
print r
cursor.close()
conn.commit()
conn.close()