Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367696
  • 博文数量: 97
  • 博客积分: 2846
  • 博客等级: 少校
  • 技术积分: 1000
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-19 20:00
文章分类

全部博文(97)

文章存档

2017年(1)

2013年(2)

2012年(6)

2011年(17)

2010年(12)

2009年(41)

2007年(18)

我的朋友

分类: Mysql/postgreSQL

2009-07-16 21:01:23

Python访问MYSQL的使用
首先要开启mysql。这样才能访问。
1,下载访问MYSQL的python包:
2,安装,我用的windows下直接next。
3,访问:
a,建立一个MySQLdb的类实例。conn = MySQLdb.connect
(host="localhost",user="root",passwd="ss",db="mytable")返回连接对象。
host:Mysql主机
user:连接使用的用户名
passwd:连接使用的用户名密码
db:默认打开的数据库
b,获取数据库指针(当前指向数据库的指针)。cursor = conn.cursor()
c,获取数据库信息(select是mysql的命令)。执行cursor.execute('select * from tables')
d,获取一row。fetchone(),类似readline(),每次返回row的tuple
e,移动指针。相当于f.seek()。cursor.scroll(int, parm)。
int:移动的行数,整数;在相对模式下,正数向下移动,负值表示向上移动。
parm:移动的模式,默认是relative,相对模式;可接受absoulte,绝对模式。
f,修改数据:括号内为mysql的命令
cursor.execute("insert  into table (row1, row2) values ('111', '222')")
cursor.execute("update  table set   row1 = 'test'  where  row2 = 'row2' ")
cursor.execute("delete from  table  where row1 = 'row1' ")
有时候会这样写:
sql="insert into note (note_id,note_detail) values (%s,%s)"  
param=('600000',"aaaa")   
cursor.execute(sql,param)
g,修改确认:conn.commit()
h,访问完后,关闭
cursor.close()
conn.close()
类似于f.close()

上代码:

 

import MySQLdb
conn = MySQLdb.connect(host="localhost",user="root",passwd="123",db="test")
conn.select_db("test")
cursor = conn.cursor()
cursor.execute("select * from table1")    # print all table1
# cursor.execute("insert into shop values(1,'a')")    # insert row
# conn.commit()            # commit update
sd = cursor.fetchall()    # fetch the table1
print sd         
cursor.close()        # close
conn.close()

阅读(1994) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~