Python 下 pymsql 库的基本使用
库的导入
import pymysql
连接 MySql
- 连接配置 从上往下依次是主机 ip,数据库名,用户名及密码。
1
2
3
4MYSQL_HOST = 'localhost'
MYSQL_DBNAME = 'cnkiQuote'
MYSQL_USER = 'root'
MYSQL_PASSWD = '123456' - 连接 指定编码为 utf8
1
2
3
4
5
6
7connection=pymysql.connect(
host=MYSQL_HOST,
db=MYSQL_DBNAME,
user=MYSQL_USER,
passwd=MYSQL_PASSWD,
charset='utf8',
use_unicode=True)
Sql 操作
查询
1
2
3
4connection.cursor.execute("""select * from periodical_data where title = %s and publicationDate = %s and author = %s""",
(item["title"],
item['publicationDate'],
str(item['author'])))插入
1
2
3
4
5
6
7connection.cursor.execute("""insert into periodical_data(title,author,journalName,publicationDate,referenceNum, downloadNum) value (%s,%s,%s,%s,%s,%s)""",
(item['title'],
str(item['author']),
item['journalName'],
item['publicationDate'],
item['referenceNum'],
item['downloadNum']))更新
1
2
3
4
5
6
7
8
9
10connection.cursor.execute("""update periodical_data set title = %s,author = %s,journalName = %s, publicationDate = %s,referenceNum = %s,downloadNum = %s where title = %s and publicationDate = %s and author = %s""",
(str(item['title']),
str(item['author']),
str(item['journalName']),
item['publicationDate'],
item['referenceNum'],
item['downloadNum'],
str(item['title']),
item['publicationDate'],
str(item['author'])))提交更改
connection.commit()