学习MySQLdb

Python提供了一条规范(DB-API),来规定以一致的方式操作各个数据库。有了这个规范,当更改数据库的时候,代码可以不改动。这个MySQLdb,就是用来操作mysql数据的。这个规范在[2]中有说明,[3]中说了一些MySQLdb特殊的地方。所以,要会用MySQLdb,先看[2],在看[3],操作数据库的方式看[1].

MySQLdb是对_mysql的一个封装,而_mysq对应的是MySQL C API.

一些代码

import MySQLdb
def myconnect():
    try:
        # connect
        mydb=MySQLdb.connect(host='localhost',user='root',passwd='orchid',db='test')
        cur=mydb.cursor()
        
        #create new table
        createsql='''
                    CREATE TABLE IF NOT EXISTS Persons
                            (
                            P_Id int,
                            LastName varchar(255),
                            FirstName varchar(255),
                            Address varchar(255),
                            City varchar(255)
                            )
                '''
        cur.execute(createsql)
        
        #select
        selectsql='SELECT * FROM Persons'
        cur.execute(selectsql)
        for row in cur.fetchall():
            print row
        


        #insert
        insertsql='INSERT INTO Persons (P_Id,LastName,FirstName,Address,City) VALUES (%s,%s,%s,%s,%s)'
        cities=[(1,'zhu','daisy','Xueyuang','BJ'),(2,'zhu','orchid','Xueyuang','BJ')]
        n=cur.executemany(insertsql,cities)
        print n
        mydb.commit()
            
        mydb.close()
        cur.close()
        
    except MySQLdb.Error,e:
        print e

参考资料:

[1]MySQL 5.6 Reference Manual : http://dev.mysql.com/doc/refman/5.6/en/index.html

[2]PEP 249 -- Python Database API Specification v2.0 : http://www.python.org/dev/peps/pep-0249/

[3]MySQLdb User's Guide : http://mysql-python.sourceforge.net/MySQLdb.html

[4]SQL 教程: http://www.w3schools.com/sql/

posted @ 2013-03-26 19:53  orchid  阅读(252)  评论(0编辑  收藏  举报