Welcome 微信登录

首页 / 数据库 / MySQL / Python对MySQL的CRUD

Python对各种数据库的各种操作满大街都是,不过,我还是喜欢我这种风格的,涉及到其它操作,不过重点还是对数据库的操作。Python操作MySQL首先,我习惯将配置信息写到配置文件,这样修改时可以不用源代码,然后再写通用的函数供调用新建一个配置文件,就命名为conf.ini,可以写各种配置信息,不过都指明节点(文件格式要求还是较严格的):[app_info]
DATABASE=test
USER=app
PASSWORD=123456
HOST=172.17.1.1
PORT=3306[mail]
host=smtp.linuxidc.com
mail_from=linuxidc0111@linuxidc.com
password=654321
send_to=linuxidc0111@linuxidc.com;linuxidc0111@linuxidc.com同目录下新建文件db.py,精悍的代码如下,不解释:# -*-coding:utf-8 -*-import MySQLdb #首先必须装这两个包
import ConfigParsercf=ConfigParser.ConfigParser()
cf.read("conf.ini")DATABASE=cf.get("app_info","DATABASE")
USER=cf.get("app_info","USER")
PASSWORD=cf.get("app_info","PASSWORD")
HOST=cf.get("app_info","HOST")
PORT=cf.get("app_info","PORT")def mysql(sql):
    try:
        conn=MySQLdb.connect(host=HOST,user=USER,passwd=PASSWORD,db=DATABASE,port=PORT)
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchall()
        conn.commit()  #这个对于增删改是必须的,否则事务没提交执行不成功
        cur.close()
        conn.close()
        return rows
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])上面是封装了操作数据库的方法,只需提供一个sql语句,CRUD均可操作。下面来YY一些数据来测试下增删改查的具体用法(easy的,我真是闲),接着上面的代码写:def operation():
    #查询
    select = mysql("select * from test")    #插入
    """
    插入这个地方有2点需要注意:
    1.插入某几列如下指定,插入全部可以不指定列,但必须后面插入的值要按顺序
    2.注意下面的type列两边有反斜点,这是因为type在我这个数据库里有个表也叫这个,或者可以把它叫关键字,不加反斜点插入会失败
    3.这没好说的,呵呵,数字占位符用%d,字符串用%s,且字符串占位符必须用双引号括起来
    """
    insert = mysql("insert into test (name,number,`type`) values("%s",%d,"%s")"%("jzhou",100,"VIP"))    #更新
    mysql("update test set number=%d where name="%s""%(99,"jzhou"))    #删除
    delete = mysql("delete from test where number = %d and `type`="%s""%(100,"jzhou"))    return select #我返回这个是为了下面发送邮件用的,顺便增加个发送邮件的功能我只是想把这个简单的操作搞的复杂点,增加个发送邮件的功能,也是接着上面的代码:mailto_list=[]
send_info=cf.get("mail","send_to")
send_array=send_info.split(";")
for i in range(len(send_array)):
    mailto_list.append(send_array[i])mail_host=cf.get("mail","host")
mail_from=cf.get("mail","mail_from")
mail_password=cf.get("mail","password")def send_mail(to_list,sub,content):
    me=mail_from
    msg=MIMEText(content,_subtype="html",_charset="utf-8")
    msg["Subject"]=sub
    msg["From"]=me
    msg["To"]=";".join(to_list)
    try:
        s=smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_from,mail_password)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False发送邮件的配置我也是写在conf.ini里的,在主函数里调用一下发送邮件来结束这个东西:if __name__ == "__main__":
    sub = u"不要问我为什么写这篇博客,闲,就是任性!"
    content = operation()
    if send_mail(mailto_list,sub,content):
        print "send success"
    else:
        print "send failed"其实我还想说一下python操作postgresql,跟mysql非常类似,下载包psycopg2,不太相同的就是postgresql中执行的sql语句都要加双引号,来感受一下:# -*-coding:utf-8 -*-
import psycopg2
import ConfigParsercf=ConfigParser.ConfigParser()
cf.read("conf.ini")DATABASE=cf.get("cmdb_info","DATABASE")
USER=cf.get("cmdb_info","USER")
PASSWORD=cf.get("cmdb_info","PASSWORD")
HOST=cf.get("cmdb_info","HOST")
PORT=cf.get("cmdb_info","PORT")def psql(sql):
    try:
        conn = psycopg2.connect(database=DATABASE, user=USER, password=PASSWORD, host=HOST, port=PORT)
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchall()
        conn.commit()
        cur.close()
        conn.close()
        return rows
    except Exception,e:
        print edef psql_oper():
    sql="select "name","type" from "test" where "name" = "jzhou""
    rows=psql(sql)
    print rows我总结了下,此博客虽简单,但包含三个重要的知识点,^_^1、python读取ini文件(要import ConfigParser)2、python操作mysql3、python发送邮件4、发表出来的都是经过实践检验的,即使很简单,这是一种态度!--------------------------------------分割线 --------------------------------------CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里 本文永久更新链接地址