python

'''Insert items into database@author: hakuri'''import MySQLdbdef InsertData(TableName,dic): try: conn=MySQLdb.connect(host='localhost',user='root',passwd='****',db='test',port=3306) #链接数据库 cur=conn.cursor() COLstr='' #列的字段 ROWstr='' #行字段 ColumnStyle=' VARCHAR(20)' for key in dic.keys(): COLstr=COLstr+' '+key+ColumnStyle+',' ROWstr=(ROWstr+'"%s"'+',')%(dic[key]) #判断表是否存在,存在执行try,不存在执行except新建表,再insert try: cur.execute("SELECT * FROM %s"%(TableName)) cur.execute("INSERT INTO %s VALUES (%s)"%(TableName,ROWstr[:-1])) except MySQLdb.Error,e: cur.execute("CREATE TABLE %s (%s)"%(TableName,COLstr[:-1])) cur.execute("INSERT INTO %s VALUES (%s)"%(TableName,ROWstr[:-1])) conn.commit() cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) if __name__=='__main__': dic={"a":"b","c":"d"} InsertData('testtable',dic)
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号