python 使用MySQLdb连接mysql,pythonmysqldb,MySQLdb顾名思义,


MySQLdb顾名思义,这个包是python连接mysql的包

# 打开数据库conn = MySQLdb.connect(**self.options.mysql_conn_params)cursor = conn.cursor()table_name = "oostat_%d_d" % (today.year, today.month)# 创建数据表try:    if new_table:sql = "CREATE TABLE IF NOT EXISTS %s LIKE oostat" % table_namecursor.execute(sql)except Exception as e:    log.err(e)# 数据入库try:    sql = "INSERT INTO " + table_name + "(devid, name, time, stat) VALUES(%s, %s, NOW(), %s)"    cursor.executemany(sql, values)except Exception as e:    log.err(e)# 关闭连接cursor.close()conn.commit()       # ! 重要,不要忘了提交conn.close()

注意事项:

连接时一定要指定 charset,否则是 latin-1,不管 mysql 是什么样的配置修改数据后,关闭连接前,一定要执行 commit,执行了大不了是个空操作,不执行可能数据就不知道哪里去了

可以用 executemany 执行多个查询

评论关闭