A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

[Python学科]MySqldb基本操作文档MySqldb基本操作文档

1. unbutu下安装MySQLdb模块
sudo apt-get install python-mysqldb
复制代码

2. 导入MySQLdb模块
import MySQLdb
复制代码


3. MySQLdb操作数据库的API函数
a)connect函数
方法:
connection(host, user, passwd, db, port, charset)
函数功能:
提供的connect方法用来和数据库建立连接。
返回值:
返回连接对象。
参数:
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
更多关于参数的信息可以查这里
http://mysql-python.sourceforge.net/MySQLdb.html
复制代码

b)cursor函数
方法:
cursor()
函数功能:
使用连接对象获得一个cursor对象cur,得用这个对象可以执行一系列命令。
返回值:
返回值为获得的一个cursor对象。
参数:
无。
复制代码
c)execute函数
方法:
execute(self, query, args)
函数功能:
执行单条sql语句。
返回值:
返回值为受影响的行数。
参数:
query为sql语句。
args为使用的参数列表。


复制代码


d)executemany函数
方法:
executemany(self, query, args)
函数功能:
执行单条sql语句,但是重复执行参数列表里的参数。
返回值:
返回值为受影响的行数。
参数:
query为sql语句。
args为使用的参数列表。
复制代码
e)fetchall函数
方法:
fetchall(self)
函数功能:
接收全部的返回结果行。
返回值:
返回值为结果行的列表。
参数:


复制代码
f)commit()函数
方法:
commit(self)
函数功能:
提交事务,否则对数据库所做的操作不会更新到数据库中。
返回值:

参数:


复制代码
g)close()函数
方法:
close(self)
函数功能:
关闭数据库链接,分别的关闭指针对象和连接对象.他们有名字相同的方法。
cur.close() conn.close()
返回值:

参数:

复制代码

4. 示例代码
a)向数据库中插入数据
#! /usr/bin/python
#coding=utf-8

import MySQLdb

conn=MySQLdb.connect(host='localhost', user='root', passwd='root', db='test')
cur = conn.cursor()

#执行select语句,返回受影响的行数
count = cur.execute('select * from user')
print '一共有%d行数据' %count

#获取结果集中的第一条数据
res = cur.fetchone()
print 'name:%s age:%d' %res
print '='*6

#从当前cursor的位置处获取5条数据
res = cur.fetchmany(5)
for r in res:
    print 'name:%s age:%d' %r

print '='*6
#讲cursor重新移动到结果集的第一条数据
cur.scroll(0, mode='absolute')
#获取结果集中的所有数据
res = cur.fetchall()
for r in res:
    print 'name:%s age:%d' %r
print '='*6
#讲cursor重新移动到结果集的第一条数据
cur.scroll(0, mode='absolute')
#获取结果集中的所有数据
res = cur.fetchall()
for r in res:
    print 'name:%s age:%d' %r

cur.close()
conn.close()
复制代码



c)更新数据库中的数据

#! /usr/bin/python
#coding=utf-8

import MySQLdb

conn=MySQLdb.connect(host='localhost', user='root', passwd='root', db='test')
cur = conn.cursor()

#执行select语句,返回受影响的行数
count = cur.execute("update user set age = 18 where name='susu'")
print '一共更新了%d行数据' %count

cur.close()
conn.close()
复制代码
d)删除数据库中的数据

#! /usr/bin/python
#coding=utf-8

import MySQLdb

conn=MySQLdb.connect(host='localhost', user='root', passwd='root', db='test')
cur = conn.cursor()

#执行select语句,返回受影响的行数
count = cur.execute("delete from where name='susu'")
print '一共删除了%d行数据' %count

cur.close()
conn.close()
复制代码

1 个回复

倒序浏览
我来占层楼啊   
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马