1. python 使用mysql
import MySQLdb
报错:“ImportError: No module named ‘MySQLdb’”
pip install mysqlclient
问题原因:
python2和python3在数据库模块支持这里存在区别,python2是mysqldb,而到了python3就变成mysqlclient
2. 向 mysql 批量插入数据
import MySQLdb
def conn():
db = MySQLdb.connect(host='xxxxxx', user='xxxx', passwd='xxxx', port=3306, charset='utf8')
db.select_db('xxxx')
cursor = db.cursor()
return cursor, db
def test():
result = [('1', '2', '3', '4', '5'), ('11', '22', '33', 44)]
cursor, db = conn()
# 注意:列名不用加引号
# list转tuple: tuple(list)
sql = "insert into contents(title, author, publish_time, content, images) values (%s, %s, %s, %s, %s)"
try:
cursor.executemany(sql, tuple(result))
db.commit()
except Exception as e:
print(str(e))
db.rollback()
cursor.close()
db.close()
if __name__ == "__main__":
test()