#!/ usr/ bin/ env python
#-*- encoding: UTF- 8-*-
"""
测试MySQL的连接及操作
"""
import MySQLdb
connstring=
"host='localhost',port=3306,user='root',passwd='*****',db='python'" #连接字符串
try:
conn= MySQLdb. connect( connstring)
except Exception, e:
print e
break
mycursor= conn. cursor()
#获取游标,用游标操作数据库
#创建表
ctable="""CREATE TABLE test if not exists(name VARCHAR(30),uid INT(10) primary key)"""
mycursor. execute( ctable)
#插入数据
insert1="""INSERT INTO test(name='aaa',uid=111)"""
insert2="""INSERT INTO test(name='bbb',uid=222)"""
insert3="""INSERT INTO test(name='ccc',uid=333)"""
inserts=[]
inserts[ 0]. append( insert1)
inserts[ 1]. append( insert2)
inserts[ 2]. append( insert3)
for insert in inserts:
try:
mycursor. execute( insert)
except Exception, e:
print e
#删除数据
#注释掉,下边查询要用到数据,只记录操作
#mycursor. execute("""DELETE FROM test WHERE name='aaa'""") #多表删除
#delmany="""" DELETE FROM table1, table2, table3 WHERE table1. uid= XXX AND table2. uid= table3. uid"""
#mycursor.execute(delmany)
继续......
以上是基本操作,补充几个对象的方法和属性:
1.connection(连接)对象:
方法名作用
close() 关闭数据库
commit() 提交当前事务
rollback() 取消当前事务
cursor() 获取当前连接的游标对象
errorhandler(cxn,cur,errcls,errval) 作为已给游标的句柄
2.cursor游标对象属性及方法:
属性方法描述
arraysize 使用fetchmany()方法时一次取出的记录数,默认为1
connection 创建此游标的连接(可选)
discription 返回游标的活动状态,包括(7元素):
(name,type_code,display_size,internal_size,precision,scale,null_ok)其中name,type_code是必须的。
lastrowid 返回最后更新行的ID(可选),如果数据库不支持,返回None
rowcount 最后一次execute()返回或影响的行数
callproc(func[,args]) 调用一个存储过程
close() 关闭游标
execute(op[,args]) 执行sql语句或数据库命令
executemany(op,args) 一次执行多条sql语句,执行的条数由arraysize给出fetchone() 匹配结果的下一行
fetchall() 匹配所有剩余结果
fetchmany(size-cursor,arraysize) 匹配结果的下几行
__iter__() 创建迭代对象(可选,参考next())
messages 游标执行好数据库返回的信息列表(元组集合)
next() 使用迭代对象得到结果的下一行
nextset() 移动到下一个结果集(如果支持的话)
rownumber 当前结果集中游标的索引(从0行开始)
setinput-size(sizes) 设置输入最大值
setoutput-size(sizes[,col]) 设置列输出的缓冲值
python连接MySQL数据库讲解
模块功能:connect()方法
* connect()方法用于连接数据库,返回一个数据库连接对象。
如果要连接一个位于服务器上名为fourm的MySQL数据库,连接串可以这样写:
db = MySQLdb.connect(host="",user="user",passwd="xxx",db="fourm" ) connect()的参数列表如下:
host,连接的数据库服务器主机名,默认为本地主机(localhost)。
user,连接数据库的用户名,默认为当前用户。
passwd,连接密码,没有默认值。
db,连接的数据库名,没有默认值。
conv,将文字映射到Python类型的字典。
默认为MySQLdb.converters.conversions cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。
compress,启用协议压缩功能。
named_pipe,在windows中,与一个命名管道相连接。
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。
read_default_file,使用指定的MySQL配置文件。
read_default_group,读取的默认组。
unix_socket,在unix中,连接使用的套接字,默认使用TCP。
port,指定数据库服务器的连接端口,默认是3306。
* 连接对象的db.close()方法可关闭数据库连接,并释放相关资源。
* 连接对象的db.cursor([cursorClass])方法返回一个指针对象,用于访问和操作数据库中的数据。
* 连接对象的db.begin()方法用于开始一个事务,如果数据库的AUTOCOMMIT已经开启就关闭它,直到事务调用commit()和rollback()结束。
*连接对象的mit()和db.rollback()方法分别表示事务提交和回退。
*指针对象的cursor.close()方法关闭指针并释放相关资源。
*指针对象的cursor.execute(query[,parameters])方法执行数据库查询。
*指针对象的cursor.fetchall()可取出指针结果集中的所有行,返回的结果集一个元组(tuples)。
*指针对象的cursor.fetchmany([size=cursor.arraysize])从查询结果集中取出多行,我们可利用可选的参数指定取出的行数。
*指针对象的cursor.fetchone()从查询结果集中返回下一行。
*指针对象的cursor.arraysize属性指定由cursor.fetchmany()方法返回行的数目,影响fetchall()的性能,默认值为1。
*指针对象的cursor.rowcount属性指出上次查询或更新所发生行数。
-1表示还没开始查询或没有查询到数据。
模块功能演示
#!/usr/bin/python
import MySQLdb
try:
connection = MySQLdb.connect(user="user",passwd="password",host="xxx",db="test") except:
print "Could not connect to MySQL server."
exit( 0 )
try:
cursor = connection.cursor()
cursor.execute( "SELECT note_id,note_detail FROM note where note_id = 1" ) print "Rows selected:", cursor.rowcount
for row in cursor.fetchall():
print "note : ", row[0], row[1]
cursor.close()。