引用pymysql模組連線mysql

2021-08-26 12:41:43 字數 2471 閱讀 2050

1.要使用python的pymysql庫對mysql資料庫進行操作時,要先在ubuntu想安裝pymysql庫。

安裝過程:

***:安裝好pip3之後,用命令:pip install python3-pymysql 安裝pymysql庫,一直按y即可。

2.安裝好pymysql之後,就可以在ubuntu進行資料庫的連線

連線的步驟如下:

import pymysql

con=pymysql.connect(

host='localhost',#設定本地連線,如果非本地就輸入資料庫的ip

user='root',#資料庫的使用者名稱

passwd='password',#密碼

charset='utf8'#或者utf8mb4

db='db_name'#連線的資料庫的名字

)#此後就可以建立游標對所連線的資料庫進行操作了

cursor=con.cursor()

先導入pymysql模組,再用.connect()函式進行連線,connect函式的引數如上所示,根據自己的資料庫實際情況填寫即可

本部落格的主要目的並不是教大家怎麼連線mysql資料庫,其實在網上就有很多這樣的教程,比我的更詳細的很多,大家自己多去檢視就是了

這是很正常的,因為我們在安裝資料庫和建立資料庫使用者的時候都會有設定的錯誤,或者沒有修改預設的設定,這些都要大        家自己靠經驗的積累了。

出錯的大概原因可以告訴大家:

root@glon-virtual-machine:/home/glon# mysql

welcome to the mysql monitor. commands end with ; or \g.

your mysql connection id is 23

server version: 5.7.23-0ubuntu0.18.04.1 (ubuntu)

oracle is a registered trademark of oracle corporation and/or its

affiliates. other names may be trademarks of their respective

owners.

type 'help;' or '\h' for help. type '\c' to clear the current input statement.

mysql> select user,plugin from mysql.user;

+------------------+-----------------------+

| user | plugin |

+------------------+-----------------------+

| root | auth_socket |

| mysql.session | mysql_native_password |

| mysql.sys | mysql_native_password |

| debian-sys-maint | mysql_native_password |

| glon | mysql_native_password |

+------------------+-----------------------+

即可看到資料庫下各使用者的plugin是不同的,其實root的是auth_socket,而其他使用者是mysql_native_password(這裡只提示             大家兩者不同導致的連線錯誤,具體原因還需進一步**)

這時可以

方法2:不使用root使用者,而是使用其他普通使用者,並且加上這兩句命令:

mysql>>grant all privileges on *.* to 'your_system_user'@'localhost';

mysql>>flush privileges;

這就解決了問題了

錯誤2:pymysql.err.operationerror:(1044:後面的忘了,大體原因差不多)

這時,出錯的原因是因為所連線的資料庫的問題,如果你把.connect()函式中的  db  引數注釋掉,你會發現沒有錯誤                了,這都是所建立的資料庫的許可權問題,只要加上下面的語句就可以解決:

grant all privileges on db_name.* to 'username'@localhost identified by 'password'; 

flush privileges;

綜上所述,mysql連線錯誤都是資料庫的設定問題導致出錯的,所以大家在學習mysql或者其他的資料庫的時候要多去鑽研其中的設定問題,了解資料庫裡面的許可權和設定的原理,以便可以在發現錯誤的時候及時感悟到錯誤所在。

pymysql包使用(python操縱mysql)

4 更新資料 5 刪除資料 import pymysql db pymysql.connect host localhost user root password 123 port 3306 cursor db.cursor cursor 方法獲取mysql操縱游標,用於執行sql語句 cursor...

python3 安裝pymysql連線模組

在使用 pymysql 之前,我們需要確保 pymysql 已安裝。如果還未安裝,我們可以使用以下命令安裝最新版的 pymysql pip install pymysql如果你的系統不支援 pip 命令,可以使用以下方式安裝 py install2 如果需要制定版本號,可以使用 curl 命令來安裝...

pymysql模組用法

pymsql是python中操作mysql的模組,其使用方法和py2的mysqldb幾乎相同。1 pip install pymysql import pymysql 新增資料 conn pymysql.connect host 127.0.0.1 port 3306,user root passw...