Python3操作資料庫
阿新 • • 發佈:2019-01-05
參考:
PyMySQL 是在 Python3.x 版本中用於連線 MySQL 伺服器的一個庫,Python2中則使用mysqldb。
通常使用的方法包括:連線、建表、增刪查改、事務處理。
sql語句備註:# -*- 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()
SELECT message FROM fcomment;
ALTER TABLE fcomment ADD column sentiment VARCHAR(10) AFTER message;
UPDATE fcomment SET sentiment = '%s' WHERE id='" + i + "';
將Dataftame寫入MySQL資料庫