zoukankan      html  css  js  c++  java
  • Python调用MySQL的一些用法小结

    目标:1个excel表内容导入到数据库中,例如:原始excel文件为 aaa.xls 

    首先:将aaa.xls 转换成aaa.txt ,注意当文件中含有中文字符时,可以通过notepad++打开,在“格式”下选择转存为utf8格式或者选择utf8格式再另存

    即:

    txtFile = aaa.txt

    #引入MySQLdb库,这个库的安装再另外写

    import MySQLdb

    #定义数据库的接入

    def getDbAccessConf( confFileName ):

    dbIp = "unknown"
    dbUser = "unknown"
    dbPasswd = "unknown"
    dbName = "unknown"

    patternDbIp = r"(.*)dbIp(.*)=(.*)"
    patternDbUser = r"(.*)dbUser(.*)=(.*)"
    patternDbPasswd = r"(.*)dbPasswd(.*)=(.*)"
    patternDbName = r"(.*)dbName(.*)=(.*)"

    fileData = open(confFileName)
    lines = fileData.readlines()

    for line in lines:
    matchObj = re.match( patternDbIp, line )
    if matchObj:
    dbIp = matchObj.group(3).strip()

    matchObj = re.match( patternDbUser, line )
    if matchObj:
    dbUser = matchObj.group(3).strip()

    matchObj = re.match( patternDbPasswd, line )
    if matchObj:
    dbPasswd = matchObj.group(3).strip()

    matchObj = re.match( patternDbName, line )
    if matchObj:
    dbName = matchObj.group(3).strip()

    return dbIp, dbUser, dbPasswd, dbName

    #定义数据内容的插入
    def insertIntoDb( db ):
    tableHeadMobile = 'mobileHead'
    idxRow = 0;
    cursor = db.cursor()

    f= open('ccc.txt','r')
    for row in f:
    contents = row.split(' ')
    operator = contents[0]
    #print ' ope: ' + operator,
    for idx in range( 1, len(contents) ):
    headMobile = contents[idx]
    if "" == headMobile:
    print 'headMobile is empty. head=' + headMobile
    continue

    sqlComm = 'select count(id) from ' + tableHeadMobile + ' where headMobile = "' + headMobile + '"'
    cursor.execute( sqlComm )
    sqlData = cursor.fetchall()
    rowNum = sqlData[0][0]
    if 0 == rowNum:
    sqlComm = 'insert into ' + tableHeadMobile + ' values( "' + str(idxRow) + '", "' + operator + '", "' + headMobile + '" )'
    print sqlComm
    cursor.execute( sqlComm )
    idxRow = idxRow + 1

    db.commit()
    cursor.close()

  • 相关阅读:
    springmvc整合elasticsearch
    测试中出现ERROR StatusLogger No log4j2 configuration file
    SpringBoot项目取消数据库配置
    centos7 更换jdk版本
    对前后端解耦的理解
    满足java对redis的所有操作,token,验证码过期时间等
    在spring的过滤器中注入实体类(@autowire会失效可使用这个方法)
    linux 下vim中关于删除某段,某行,或全部删除的命令
    解决问题Can’t connect to local MySQL server through socket
    centos6.5 mqtt安装
  • 原文地址:https://www.cnblogs.com/wangzhao2016/p/5596136.html
Copyright © 2011-2022 走看看