• python基础总结篇——使用Mysql


    python操作Mysql,很方便,使用的MySQLdb的库,基本的操作如下:

    查询:

     1 try:
     2     conn = MySQLdb.connect(host=self.ip, user=self.username,passwd=self.password, db=self.dbname, port=self.port)
     3     cur = conn.cursor()
     4     cur.execute(sql)
     5     rows = cur.fetchall()
     6     data = rows
     7 except MySQLdb.Error, e:
     8     print str(e)
     9     print "Connet mysql db error..."
    10     sys.exit()

    插入数据:

    try:
        conn = MySQLdb.connect(host=self.ip, user=self.username, passwd=self.password, db=self.dbname, port=self.port)
        cur = conn.cursor()
        cur.execute(sql, value)
        conn.commit()
        conn.close()
        cur.close()
    except MySQLdb.Error, e:
        print str(e)
        print "Execute mysql db error..."
        sys.exit()

    使用过程中遇到了编码的问题,使用utf-8解决编码问题:

    conn.set_character_set('utf8')
    cur.execute('SET NAMES utf8;')
    cur.execute('SET CHARACTER SET utf8;')
    cur.execute('SET character_set_connection=utf8;')

    还有遇到反斜杠的问题,mysql默认把反斜杠转义了,我的解决方法是将反斜杠换成双反斜杠:

    datapath = datapath.replace('\', '\\')

    mysql语句需要格式化字符串,查询的sql字符串需要用%来代表变量占位,不过python好像必须要用%s

    executemany还支持多条数据同时插入,不过我没有使用这个,因为在外面加循环处理也很方便。

  • 相关阅读:
    Python环境变量的配置
    关于selenium+python的googledirver和iedirver的配置
    jdk1.6环境变量配置
    windows server 2012R2安装激活码
    Git生成SSHKey
    Linux下配置和安装VNCServer远程服务
    Win7 64位硬盘安装Ubuntu 64位的细微配置
    apache tomcat 8.0 显示目录文件
    跨域登录
    jsonp 代码优化
  • 原文地址:https://www.cnblogs.com/crazymanpj/p/5771129.html
Copyright © 2020-2023  润新知