寫python腳本的時候,常常用到的方法

#!/usr/bin/env python
#encoding=utf-8
import os
import sys
import MySQLdb
import string
import time

def isAString(anobj): 
    return isinstance(anobj, basestring) 

def gen_insert_sql(dict,table):
    cols   = ''
    values = ''
    count  = 1
    for (k,v) in dict.items():  
        cols = cols + k
        if count != len(dict):
            cols = cols +','
        if type(v) == str:
            v  = "'" + v +"'"
        else:
            v = str(v)
        values = values + v
        if count != len(dict):
            values = values +','
        count  = count + 1
    sql    = 'replace  into %s  (%s) values (%s)' % (table,cols,values)
    return sql
def getConn(url,username,passwd,db,port):
    conn = MySQLdb.connect(host=url, user=username, passwd=passwd,db=db,port=port)
    cursor = conn.cursor()
    cursor.execute("SET NAMES utf8")
    cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
    cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
    return conn,cursor

def dateRange(start, end, step=1, format="%Y-%m-%d"):
    strptime, strftime = datetime.datetime.strptime, datetime.datetime.strftime
    days = (strptime(end, format) - strptime(start, format)).days
    return [strftime(strptime(start, format) + datetime.timedelta(i), format) for i in xrange(0, days, step)]
相關文章
相關標籤/搜索