conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='*******',
database='wangyi')
cur = conn.cursor(pymysql.cursors.DictCursor)
try:
sql = "insert into news(title, content, keyword,type) values(%s, %s, %s,%s);"
# 数据库中有id字段,使用executemany 向数据库中提交!
print(sql)
ret = self.cur.executemany(sql,[(item['new_title'],item['new_content'],word,type)])# 执行sql 语句
#有几个占位符 列表里面的元组就应该有几个元素,否则的就存不进去,
#如果数据库里面有id 字段,而这里的sql语句中又没有写id字段,那么在用execute方法执行sql语句的时候,会报错!!!!
#因此就用 executemany 这样提交数据才会成功1
rint(ret)
self.conn.commit() # 提交数据
res = self.cur.fetchall() # 返回插入的结果
except:
self.conn.rollback() # 回滚
#执行完之后
cur.close()
conn.close()
#删除:
cur.execute('delete from teacher where tname="cting";')
# 修改
cur.execute('update 表名 set 字段名 = 值,字段名 = 值 where 条件;')
cur = conn.cursor(pymysql.cursors.DictCursor) # 设置返回的数据类型是字典
ret = cur.fetchone() # 这个语句执行一次返回一个结果
ret = cur.fetchone() # 可以多次执行