python 操作mysq


MySQLdb下载地址:http://sourceforge.net/projects/mysql-python/
MySQL-python-1.2.2.win32-py2.5.exe
直接安装就行.

其他:

1.   平台及版本
linux 内核2.6,gcc 3.4.4,glibc 2.4
python 2.4.3
mysql 5.0.19
mysql-python 1.2.1-p2
2.   安装mysql-python
tar xvfz MySQL-python-1.2.1_p2.tar.gz
cd MySQL-python-1.2.1_p2
python setup.py build
python setup.py install


3.   使用
import MySQLdb
3.1.   连接
conn =   MySQLdb.Connection(host, user, password, dbname)
3.2.   选择数据库
 conn.select_db(’database name’)
3.3.   获得cursor
cur =   conn.cursor()
3.4.   cursor位置设定
cur.scroll(int, mode)
mode可为相对位置或者绝对位置,分别为relative和absolute。

例如:
from MySQLdb import *

def conn():
 conn=Connection("localhost","root","root")
 conn.select_db('test')
 cur=conn.cursor()
 cur.execute('select * from user_v_o')
 cur.scroll(0)
 row1=cur.fetchone()
 print row1[0]
 print row1[1]
 print  row1[2]


if __name__=='__main__':
 conn()

3.5.   select
cur.execute(‘select clause’)
例如
cur.execute(‘select * from mytable’)

 

row = cur.fetchall()
或者:
row1 = cur.fetchone()
3.6.   insert
cur.execute(‘inset clause’)
例如
cur.execute(‘insert  into table (row1, row2) values (/’111/’, /’222/’)’)

 

conn.commit()

 

3.7.   update
cur.execute(‘update  clause’)
例如
cur.execute(“update  table set   row1 = ‘’  where  row2 = ‘row2 ‘  ”)

 

conn.commit()

 

3.8.   delete
cur.execute(‘delete  clause’)
例如
cur.execute(“delete from  table  where   row1 = ‘row1’  ”)

 

conn.commit()


4.  乱码问题:
在mysql服务器也要配成utf8.

# -*- coding: cp936 -*-
from MySQLdb import *
import sys
def conn():
 conn=Connection(host="localhost",user="root",passwd="root",charset="utf8")
 conn.select_db('test')
 cur=conn.cursor()
 cur.execute('select * from user_v_o  where user_id =824')
 cur.scroll(0)
 row1=cur.fetchone()
 print row1[0]
 print row1[1]
 print  row1[3]


 #进行字符串编码转换并进行插入
 a = "浦发银行"
 a = a.decode("gbk").encode("utf-8")    #编码转换为utf-8
 sql="insert into user_v_o (user_name) values (%s)"    #生成sql语句
 param=(a)    #生成sql语句的参数
 n = cur.execute(sql,param)    #执行sql语句
 conn.commit()

if __name__=='__main__':
 conn()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值