1.连接
参数:
host='主机地址' user='用户名' passwd='密码' db='数据库名' port=端口 charset='utf8'
# 数据库连接
def Ex_Mysql():
db = pymysql.connect(host='localhost', user='root', passwd='123', db='csf', port=3306, charset='utf8')
print("数据库连接")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS dangdangweb_info_detail")
sql = """CREATE TABLE IF not EXISTS dangdangweb_info_detail (
id int auto_increment primary key,
title CHAR(100),
price CHAR(100),
source_price CHAR(100),
discount CHAR(100),
author CHAR(100),
publish_time CHAR(100),
publish CHAR(100),
comment CHAR(100)
)
DEFAULT CHARSET=utf8"""
2. 添加
# 添加
db = pymysql.connect(host='localhost', user='root', passwd='123', db='csf', port=3306, charset='utf8')
print("数据库连接")
cursor = db.cursor()
sql = "INSERT INTO dangdangweb_info_detail (title,price,source_price,discount,author,publish_time,publish,comment)\
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"%\
(str(titles), str(prices), str(source_prices), str(discounts), str(authors)
, str(publish_times), str(publishs), str(comments))
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
# 关闭数据库连接
db.close()