Python3操作数据库

参考:

https://www.cnblogs.com/woider/p/5926744.html

https://www.cnblogs.com/mooba/p/6484357.html

http://www.runoob.com/python3/python3-mysql.html

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

通常使用的方法包括:连接、建表、增删查改、事务处理。

# -*- coding: utf-8 -*-

import pymysql
import pymysql.cursors

connect = pymysql.Connect(host='',    # 远程主机的IP地址
                          user='',    # MySQL用户名
                          db='',      # 数据库名字
                          passwd='',  # 数据库密码
                          port=3306,  # 数据库监听端口,默认3306
                          charset='utf8',)  # 指定编码
# 创建游标对象
cursor = connect.cursor()

# 使用SQL语句
sql = ""
try:
    cursor.execute(sql)     # 执行SQL语句
    # db.commit()  #  若修改数据需要执行此操作
    data = cursor.fetchall()      # 获取cursor得到的数据
    # for row in data:

except:
    connect.rollback()  # 若发生错误则回滚

# 关闭连接
cursor.close()
connect.close()
sql语句备注:
SELECT message FROM fcomment; 

ALTER TABLE fcomment ADD column sentiment VARCHAR(10) AFTER message;

UPDATE fcomment SET sentiment = '%s' WHERE id='" + i + "';
将Dataftame写入MySQL数据库

猜你喜欢

转载自blog.csdn.net/sinat_36972314/article/details/79657794