学习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/

转载于:https://www.cnblogs.com/orchid/archive/2013/03/26/2983209.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值