def InsertData(TableName,dic):
try:
conn=MySQLdb.Connect(host='localhost',user='po',passwd='password',db='test',charset = 'utf8',port = 3306)
cur=conn.cursor()
COLstr='' #列的字段
ROWstr='' #行字段
ColumnStyle='VARCHAR(255)'
for key in dic.keys():
COLstr=COLstr+' '+key+' '+ColumnStyle+','
ROWstr=(ROWstr+'"%s"'+',')%(dic[key])
#判断表是否存在,存在执行try,不存在执行except新建表,再insert
try:
cur.execute("create table %s (%s)"%(TableName,COLstr[:-1]))
#print "create table %s (%s)"%(TableName,COLstr[:-1])
vsql = "insert into %s values(%s)"%(TableName,ROWstr[:-1])
vsql=vsql.encode('utf-8')#执行前重新编码
cur.execute(vsql)
#print vsql
except MySQLdb.Error,e:
cur.execute("SELECT * FROM %s"%(TableName))
#print "SELECT * FROM %s"%(TableName)
vsql = "insert into %s values(%s)"%(TableName,ROWstr[:-1])
vsql=vsql.encode('utf-8')#执行前重新编码
cur.execute(vsql)
#print vsql
#cur.scroll(0,mode='absolute')
#获取所有结果
conn.commit()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
try:
conn=MySQLdb.Connect(host='localhost',user='po',passwd='password',db='test',charset = 'utf8',port = 3306)
cur=conn.cursor()
COLstr='' #列的字段
ROWstr='' #行字段
ColumnStyle='VARCHAR(255)'
for key in dic.keys():
COLstr=COLstr+' '+key+' '+ColumnStyle+','
ROWstr=(ROWstr+'"%s"'+',')%(dic[key])
#判断表是否存在,存在执行try,不存在执行except新建表,再insert
try:
cur.execute("create table %s (%s)"%(TableName,COLstr[:-1]))
#print "create table %s (%s)"%(TableName,COLstr[:-1])
vsql = "insert into %s values(%s)"%(TableName,ROWstr[:-1])
vsql=vsql.encode('utf-8')#执行前重新编码
cur.execute(vsql)
#print vsql
except MySQLdb.Error,e:
cur.execute("SELECT * FROM %s"%(TableName))
#print "SELECT * FROM %s"%(TableName)
vsql = "insert into %s values(%s)"%(TableName,ROWstr[:-1])
vsql=vsql.encode('utf-8')#执行前重新编码
cur.execute(vsql)
#print vsql
#cur.scroll(0,mode='absolute')
#获取所有结果
conn.commit()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])