python连接mysql

1) 安装 

sudo apt-get install mysql-server
sudo apt-get install python-mysqldb

2) 使用

import MySQLdb

def get_db_connector():
    return MySQLdb.connect(host='localhost', user='root', passwd='changme', db='databaseName')

def set_db_close(conn, cur):
    conn.commit()
    cur.close()
    conn.close()

def query_one(query_str):
    try:
        conn = get_db_connector()

        cur = conn.cursor()
        cur.execute(query_str)
        record = cur.fetchone()

        set_db_close(conn, cur)

        return record
    except MySQLdb.Error, e:
        conn.rollback()#若出错,可以回滚。
        print "Error %d: %s" % (e.args[0], e.args[1])

def exist_username(username):#使用以上定义封装好的数据库操作的例子:
    query_str = "select id from user where name= '%s'" % username #name= %s is wrong!!!! it should be name= '%s'
    record = query_one(query_str)

    if record == None:
        return 0
    else :
        return 1

 

posted @ 2015-05-26 12:02  圆旭  阅读(206)  评论(0编辑  收藏  举报