From 7fd14d834e6b400a758cc201d6aa990598ca53b8 Mon Sep 17 00:00:00 2001 From: leo Date: Sat, 20 Apr 2024 13:57:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20Python?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Python.md | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Python.md diff --git a/Python.md b/Python.md new file mode 100644 index 0000000..8399152 --- /dev/null +++ b/Python.md @@ -0,0 +1,95 @@ + +## 記得安裝 pymysql +``` +pip install pymysql +``` + + + +### 資料庫連線設定 +``` +import pymysql +db = pymysql.connect(host='140.125.21.65', port=3307, user='VIP125', passwd='@VIPvip125', db='VIP125', + charset='utf8') +``` + + +### 建立操作游標 +``` +cursor = db.cursor() +``` + +### SQL語法(查詢資料庫版本) +``` +sql = 'SELECT VERSION()' +``` + +### 執行語法 +``` +cursor.execute(sql) +``` + +### 選取第一筆結果 +``` +data = cursor.fetchone() +print("Database version : %s " % data) + +``` + +### 資料讀取(全部) +``` +sql = "select * from test_0525_01" +cursor.execute(sql) +data = cursor.fetchall() +print(f'ALL_data = {data}') +``` + + +### 查詢資料(單獨) +``` +sql = "SELECT user_id FROM test_0525_01;" +cursor.execute(sql) +data = cursor.fetchall() +print(f'user_id = {data}') +``` + + +### 查詢資料(某筆) +``` +sql = "SELECT * FROM test_0525_01 WHERE user_id='1000';" +cursor.execute(sql) +data = cursor.fetchall() +print(f'user_id=1000 : {data}') + +``` + +### 刪除資料 +``` +sql = "DELETE FROM test_0525_01 WHERE user_id='1001';" +cursor.execute(sql) +db.commit() +``` + + +### 更新資料 +``` +sql = "UPDATE test_0525_01 SET user_name='user_update_1000' WHERE user_id='1000';" +cursor.execute(sql) +db.commit() +``` + + +### 資料寫入 +``` +test_data = ['1001', 'test_1001'] +sql = "INSERT INTO test_0525_01 (user_id,user_name) VALUES (%s,%s);" +cursor.execute(sql, test_data) +db.commit() +``` + + +### 關閉連線 +``` +db.close() +``` +