1. 程式人生 > >python操作mysql資料庫,pymysql

python操作mysql資料庫,pymysql

python裡操作mysql的模組是pymysql

一、安裝mysql

二、安裝pysql

pip3 install pymysql

如果是在pycharm裡安裝pymysql模組,如圖進去安裝介面,搜尋pymysql然後安裝就行。

三、使用pymysql模組

很簡單,連線——傳送sql語句執行——關閉

import pymysql

# 建立連線
'''host:主機地址;
port:mysql預設埠3306;
user:資料庫使用者名稱一般root;
passwd:安裝資料庫你設定的密碼
db:要操作的資料庫的名稱(第一次要在mysql的命令列裡先建立自己的資料庫)
charset:編碼格式'''
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='35278479', db= 'us_states', charset='utf8')

# 建立遊標,相當於mysql命令列的那個游標,可以輸入sql語句的地方
cursor = conn.cursor()

# 執行SQL,並返回收影響行數
#建立states表格,有id,state,population這3個列
effect_row = cursor.execute("CREATE TABLE states (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, state CHAR(25), population INT(9))")
print(effect_row)

#插入資料
effect_row = cursor.execute("INSERT into states (id, state, population) values (1, '加州', 5)")
print(effect_row)

effect_row = cursor.execute("select * from states")
print(effect_row)

#接受一行
row_1 = cursor.fetchone()
print(row_1)

#接受n行
row_1 = cursor.fetchone(5)
print(row_1)

#接受全部行
row_all = cursor.fetchall()
print(row_all)

# 提交,不然無法儲存新建或者修改的資料
conn.commit()

# 關閉遊標
cursor.close()

# 關閉連線
conn.close()