pymysql模組連線資料庫詳解

2021-09-27 08:41:07 字數 2188 閱讀 6887

使用方法

使用示例

由於 mysqldb 模組還不支援 python3.x,所以 python3.x 如果想連線mysql需要安裝 pymysql 模組。

pip3 install pymysql

[file] > [settings] > [project: 專案檔名] > [project interpreter] > [install按鈕]

引數解釋

host(str)

mysql伺服器位址

port(int)

mysql伺服器端口號

user(str)

使用者名稱passwd(str)

密碼db(str)

資料庫名稱

charset(str)

連線編碼

方法解釋

cursor()

使用該連線建立並返回游標

commit()

提交當前事務

rollback()

回滾當前事務

close()

關閉連線

方法解釋

execute(op)

執行乙個資料庫的查詢命令

fetchone()

取得結果集的下一行

fetchmany(size)

獲取結果集的下幾行

fetchall()

獲取結果集中的所有行

rowcount()

返回資料條數或影響行數

close()

關閉游標物件

此**僅為示例,直接複製貼上執行會報錯,因為**不變的情況下可能存在重複建表等語法錯誤

e匯入模組

import pymysql

# 建立連線

connect = pymysql.connect(host=

'localhost'

, port=

3306

, user=

'root'

, passwd=

'123456'

, db=

'fei'

)# 建立游標

cursor = connect.cursor(

)#建立資料庫表

data =

("create table ppq("

"id int primary key auto_increment,"

"time datetime,"

"my_thing varchar(177))charset=utf8; "

)#插入資料

sql_insert =

("insert into ppq(time,my_thing) values ('2019-05-13 07:32:10','smile')"

)#讀取資料

cursor.execute(

"select * from ppq"

)try

:#執行資料庫查詢命令

cursor.execute(data)

cursor.execute(sql_insert)

print

("資料庫語法操作正常。。。"

)except

:print

("您的語法存在錯誤"

)# 獲取第一行資料

row_1 = cursor.fetchone(

)print

(row_1)

# 獲取前n行資料

row_2 = cursor.fetchmany(3)

print

(row_2)

# 獲取所有資料

row_3 = cursor.fetchall(

)print

(row_3)

connect.commit(

)# 連線提交

cursor.close(

)# 關閉游標

connect.close(

)# 關閉連線

pymysql連線資料庫

建立資料庫 import pymysql 開啟資料庫連線 db pymysql.connect localhost testuser test123 testdb 使用 cursor 方法建立乙個游標物件 cursor cursor db.cursor 使用 execute 方法執行 sql,如果表...

PyMysql連線資料庫

1 先安裝pymysql模組 pip install pymysql2 匯入pymysql模組 3 連線資料庫 conn pymysql.connect host localhost user root passwd 123456 port 3306 db test1 charset utf8 cu...

pymysql連線資料庫

pymysql連線資料庫的步驟 1.匯入pymysql 2.使用 pymysql.connect host 位址,user 使用者名稱,password 密碼,port 埠,db 資料庫名 建立資料庫的連線,得到連線物件 3.獲取游標物件 con.cursor pymysql.cursors.dic...