因為MySQLdb不支持python3,需要導入pymysql
可以選擇pip 安裝pymysql,或者pycharm安裝
[File] >> [settings] >> [Project: python] >> [Project Interpreter] >> "+"
import pymysql.cursors # 連接數據庫 connect = pymysql.Connect( host='localhost', port=3310, user='root', passwd='root', db='python', charset='utf8' ) # 獲取游標 cursor = connect.cursor() # 插入數據 sql = "INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )" data = ('雷軍', '13512345678', 10000) cursor.execute(sql % data) connect.commit() print('成功插入', cursor.rowcount, '條數據') # 修改數據 sql = "UPDATE trade SET saving = %.2f WHERE account = '%s' " data = (8888, '13512345678') cursor.execute(sql % data) connect.commit() print('成功修改', cursor.rowcount, '條數據') # 查詢數據 sql = "SELECT name,saving FROM trade WHERE account = '%s' " data = ('13512345678',) cursor.execute(sql % data) for row in cursor.fetchall(): print("Name:%s\tSaving:%.2f" % row) print('共查找出', cursor.rowcount, '條數據') # 刪除數據 sql = "DELETE FROM trade WHERE account = '%s' LIMIT %d" data = ('13512345678', 1) cursor.execute(sql % data) connect.commit() print('成功刪除', cursor.rowcount, '條數據') # 事務處理 sql_1 = "UPDATE trade SET saving = saving + 1000 WHERE account = '18012345678' " sql_2 = "UPDATE trade SET expend = expend + 1000 WHERE account = '18012345678' " sql_3 = "UPDATE trade SET income = income + 2000 WHERE account = '18012345678' " try: cursor.execute(sql_1) # 儲蓄增加1000 cursor.execute(sql_2) # 支出增加1000 cursor.execute(sql_3) # 收入增加2000 except Exception as e: connect.rollback() # 事務回滾 print('事務處理失敗', e) else: connect.commit() # 事務提交 print('事務處理成功', cursor.rowcount) # 關閉連接 cursor.close() connect.close()
def insert_data(news_list): try: connect = get_connect() cursor = connect.cursor() for news in news_list: sql = "INSERT INTO news(title, tag, source, source_url, keyword, keywords) VALUES ( %s,%s,%s,%s,%s,%s)" #data = {news.title, news.tag, news.source, news.source_url, news.keyword, news.keywords} cursor.execute(sql, (news.title, news.tag, news.source, news.source_url, news.keyword, news.keywords)) connect.commit() except Exception as e: print(e) finally: cursor.close() connect.close()
def select_url(): arrList = [] try: connect = get_connect() cursor = connect.cursor() print("connection") sql = "SELECT id,source_url FROM news" cursor.execute(sql) result = cursor.fetchall() for row in result: # print(row[0]) news = News() news.source_url = row[1] arrList.append(news) except Exception as e: print(e) finally: return arrList