Python簡單操作MySQL的增,刪,改,查

2021-09-09 00:27:39 字數 3021 閱讀 5291

python操作mysql需要先安裝乙個pymysql模組。pip install pymysql

證明一下是否成功的新增環境變數,可以用cmd測試一下,win+r輸入cmd開啟命令列,輸入mysql -u 使用者名稱 -p 密碼,這樣就可以訪問到mysql了,也就是環境變數配置好了

檢視資料庫可以輸入show databases; 記得後面要加分號,不然會報錯

下面就可以用python訪問mysql了

# 開啟資料庫連線

db = pymysql.connect(

"localhost"

,"使用者名稱"

,"密碼"

,"資料庫名"

,charset=

'utf8'

)#以utf8的形式,不然會出現亂碼

# 使用cursor()方法獲取操作游標

cursor = db.cursor(

)# sql 插入語句insert into table(列,列) values (屬性,屬性)

sql =

"insert into student(id,name) values (9,'第九條記錄')"

try:

cursor.execute(sql)

# 執行sql語句

db.commit(

)#提交資料

print

("成功執行!"

)except

:print

("error: unable to fetch data"

)#列印異常

# 關閉資料庫連線

,"使用者名稱"

,"密碼"

,"資料庫名"

,charset=

'utf8'

)try

: cur = conn.cursor(

)#建立關聯資料庫的游標

cur.execute(

"select * from 表名"

)for row in cur.fetchall():

#迴圈遍歷列印資料

print

(row)

except

:print

("開啟資料庫失敗,請檢查"

# 開啟資料庫連線

db = pymysql.connect(

"localhost"

,"root"

,"abc123456"

,"student"

,charset=

'utf8'

)# 使用cursor()方法獲取操作游標

cursor = db.cursor(

)sql =

"update student set name='琳琳' where id=8"

try:

# 執行sql語句

cursor.execute(sql)

db.commit(

)print

("成功執行!"

)except

:print

("error: unable to fetch data"

)# 關閉資料庫連線

# 開啟資料庫連線

db = pymysql.connect(

"localhost"

,"root"

,"abc123456"

,"student"

,charset=

'utf8'

)# 使用cursor()方法獲取操作游標

cursor = db.cursor(

)sql =

"delete from student where id = 10"

try:

# 執行sql語句

cursor.execute(sql)

db.commit(

)print

("成功執行!"

)except

:print

("error: unable to fetch data"

)# 關閉資料庫連線

db.close(

)

通過python簡單操作MySQL

pip install pymysql開始操作前需要匯入乙個包 import mysqldb用mysqldb中的connect 函式連線對應的資料庫 連線資料庫 conn mysqldb.connect host localhost mysql的ip port 3306,預設埠3306 user r...

Python簡單操作MySQL命令安裝

安裝平台 windows py3.x pymysql是python中操作mysql的模組 執行pip3 install pymysql命令安裝 mysql版本 mysql installer community 8.0.12.0 基本命令 建立資料庫 create database student ...

用Python對MySQL簡單操作

import pymysql 連線資料庫 conn pymysql.connect host localhost user root password helloguitar532123 charset utf8 獲得浮標 cursor conn.cursor 建立資料庫 sql create cr...