#encoding=utf8
import logging
import MySQLdb
def olddb():
return DB("200db",3306,"user","password","dbname")
def newdb():
return DB("200db",3306,"user","password","dbname")
class DB():
def __init__(self,db_host,db_port,db_user,db_pwd,db_name):
self.db_host = db_host
self.db_port = db_port
self.db_user = db_user
self.db_pwd = db_pwd
self.db_name = db_name
self.conn = self.getconnection()
def getconnection(self):
return MySQLdb.connect(
host=self.db_host,
port=self.db_port,
user=self.db_user,
passwd=self.db_pwd,
db=self.db_name,
charset="utf8")
def query(self, sqlstr, params=None):
cursor = self.conn.cursor()
if params:
cursor.execute(sqlstr, params)
else:
cursor.execute(sqlstr)
res = cursor.fetchall()
self.conn.commit()
cursor.close()
self.conn.close()
return res
def saveall(self, table_name, res):
cursor = self.conn.cursor()
reslen = len(res)
if reslen > 0:
cursor.execute("""truncate table %s""" % table_name)
colums=("%s,"*len(res[0])).rstrip(',')
cursor.executemany("""insert into %s """ % table_name + """values(%s)""" % colums, res)
self.conn.commit()
print '导入完成'
else:
print '不用导入'
cursor.close()
self.conn.close()
阅读(2098) | 评论(0) | 转发(0) |