---
title: "python-MYSQLdb  "
author: "booby325"
date: "2013-01-20T20:29:31Z"
tags: []
categories: ["编程语言"]
slug: "python-mysqldb"
draft: false
lastmod: "2013-01-20T20:29:31Z"
id: 1772801
url: "https://booby325.iteye.com/blog/1772801"
---

### python-MYSQLdb

 

 

easy\_install -U MYSQL-python

二、MySQLdb的使用。

引入我们需要的包  
import MySQLdb

1.和数据库建立连接  
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")  
提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.

比较常用的参数包括  
host:数据库主机名.默认是用本地主机.  
user:数据库登陆名.默认是当前用户.  
passwd:数据库登陆的秘密.默认为空.  
db:要使用的数据库名.没有默认值.  
port:MySQL服务使用的TCP端口.默认是3306.  
conn连接有两个重要的方法commit【提交新增和修改】,rollback【撤销新增或修改】

2.执行SQL语句获取返回值  
//获取连接的游标  
cursor=conn.cursor()  
//查询  
sql = "select * from 【table】"  
//新增  
sql = "insert into 【table】(字段,字段) values(值，值)"  
//修改  
sql = "update 【table】 set 字段 =‘值’where 条件 "  
//删除  
sql = "delete from 【table】 where 条件"  
cursor.execute(sql)

返回值  
cur.execute('select * from tables')  
其返回值为SQL语句得到的行数，如：2L，表示2行。  
然后，可以从该对象的fetchone或fetchall方法得到行信息。

获取行信息  
指针对象的fetchone()方法，是每次得到一行的tuple返回值：  
引用  
&gt;&gt;&gt; row=cur.fetchone()  
&gt;&gt;&gt; print row  
('user1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/home/FTP/user1', '')

指针对象的fetchall()方法，是得到一组tuple，其内容为由行信息组成的tuple值：  
引用  
&gt;&gt;&gt; cur.scroll(0,'absolute')  
&gt;&gt;&gt; row=cur.fetchall()  
&gt;&gt;&gt; print row  
(('user1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/home/FTP/user1', ''), ('user2', '7e58d63b60197ceb55a1c487989a3720', 1000L, 1000L, '/home/FTP/user2', None))

移动指针  
当使用fetchone()方法是，指针是会发生移动的。所以，若不重置指针，那么使用fetchall的信息将只会包含指针后面的行内容。  
手动移动指针使用：  
cur.scroll(int,parm)

含义为：  
引用  
int：移动的行数，整数；在相对模式下，正数向下移动，负值表示向上移动。  
parm：移动的模式，默认是relative，相对模式；可接受absoulte，绝对模式。

修改数据  
修改数据，包括插入、更新、删除。它们都是使用指针对象的execute()方法执行：  
cur.execute("insert  into table (row1, row2) values ('111', '222')")  
cur.execute("update  table set   row1 = 'test'  where  row2 = 'row2' ")  
cur.execute("delete from  table  where row1 = 'row1' ")

因单引号“'”用于SQL语句中的标识，所以，python中的字符串需使用双引号括住。  
此外，也可以使用python的“格式化字符串”写法，简化命令，例如：  
cur.execute("update  table set   row1 = '%s'  where  row2 = '%s' " %('value1','value2'))

※请注意，'%s'的单引号是SQL语句的间隔符，'value1'的单引号是python的字符串间隔符，其含义是不同的。是否需要间隔符，以及使用双引号还是单引号作为间隔，需根据其含义决定。例如，还有：  
cur.execute("update FTPUSERS set passwd=%s where userid='%s' " %("md5('123')",'user2'))

这里，paswd=%s是因SQL的md5()函数是不需要单引号间隔的；"md5('123')"是python的字符串中含有单引号，所以用双引号括住。

 

实例:

import MySQLdb

def select(conn):  
    cursor = conn.cursor()  
    n = cursor.execute("select id, name, age, if(sex = 0, 'F', 'M') as sex from users")  
    rows = cursor.fetchall()

    for (id, name, age, sex) in rows:  
        print "id={0}, name={1}, age={2}, sex={3}".format(id, name, age, sex)

def insert(conn):  
    cursor = conn.cursor()  
    n = cursor.execute("insert into users (name, age) values (%s, %s)", ("a1", 30));  
    print "insert", n

    n = cursor.executemany("insert into users (name, age) values (%s, %s)",  
            (("a2", 30),  
             ("a3", 31),  
             ("a4", 32),  
             ("a'", 33)));  
    print "insert", n

def update(conn):  
    cursor = conn.cursor()  
    n = cursor.execute("update users set age = age + 10, sex = %s where name like %s", (1, "a%"));  
    print "update", n

def delete(conn):  
    cursor = conn.cursor()  
    n = cursor.execute("delete from users where name like %s", "a%");  
    print "delete", n

def main():  
    conn = MySQLdb.connect(host = "localhost", user = "user1", passwd = "123456", db = "test")

    try:  
        insert(conn)  
        update(conn)  
        select(conn)  
        delete(conn)  
    finally:  
        conn.close()

if \_\_name\__ == "\_\_main\_\_":  
    main()