今天無聊玩了一下Python與MySQL 真的還蠻簡單的 紀錄一下
1. Windows 10 Microsoft Store安裝 Windows Terminal
2. 安裝 Python 3.x 我是安裝 3.9
安裝好以後就可以在windows 10上面執行 python的程式了
3.安裝XAMPP
參考 : http://yhhuang1966.blogspot.com/2017/11/xampp-php.html
4.上面都安裝好以後就可以來測試資料庫了 運氣好 用其他大神的部落格範例就可以成功執行連資料庫跟搜尋了
參考 : http://yhhuang1966.blogspot.com/2018/05/python-mysql.html
範例code整理如下
import MySQLdb
conn=MySQLdb.connect(host="127.0.0.1",user="root", passwd="")
cursor=conn.cursor()
cursor.execute("SELECT VERSION()")
print("Database version : %s " % cursor.fetchone())
SQL="CREATE DATABASE IF NOT EXISTS testdb DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_unicode_ci"
cursor.execute(SQL)
conn.commit()
cursor.close() #關閉 Cursor 物件
conn.close() #關閉 Connection 物件
conn=MySQLdb.connect(host="127.0.0.1",user="root", passwd="", db="testdb", charset="utf8") #連線資料庫
cursor=conn.cursor() #傳回 Cursor 物件
SQL="CREATE TABLE IF NOT EXISTS users(\
id INT(5) PRIMARY KEY AUTO_INCREMENT,\
user_name VARCHAR(20),\
age TINYINT(3),\
gender CHAR(1),\
email VARCHAR(80),\
password VARCHAR(20))"
cursor.execute(SQL)
conn.commit() #操作結果寫入資料庫
SQL="INSERT INTO users(user_name,age,gender,email,password) VALUES('愛咪','12','女','amy@gmail.com','123')" #新增紀錄
cursor.execute(SQL)
conn.commit() #操作結果寫入資料庫
SQL="SELECT * FROM users" #查詢資料表
cursor.execute(SQL)
print(cursor.fetchone()) #擷取紀錄集
print(cursor.fetchone()) #擷取紀錄集
SQL="INSERT INTO users(user_name,age,gender,email,password) VALUES(%s, %s, %s, %s, %s)"
cursor.executemany(SQL, [('彼得',14,'男','peter@gmail.com','456'),\
('凱莉',16,'女','kelly@gmail.com','789')])
conn.commit() #操作結果寫入資料庫
SQL="SELECT * FROM users" #查詢資料表
cursor.execute(SQL)
print("fatchall")
print(cursor.fetchall()) #擷取紀錄集 (全部)
cursor.execute(SQL) #重新查詢資料表
print("fatch 2")
print(cursor.fetchmany(2)) #擷取 2 筆紀錄
cursor.execute(SQL)
print("fatch 3")
print(cursor.fetchmany(3)) #擷取 3 筆紀錄
cursor.close() #關閉 Cursor 物件
conn.close() #關閉 Connection 物件
執行結果