在Python中使用 PyMySQL 连接到 MySQL
在本文中,我们将讨论如何使用Python远程或本地连接到MySQL数据库。在下面的过程中,我们将使用Python的PyMySQL模块来连接我们的数据库。
什么是PyMySQL ?
这个包包含一个纯 Python MySQL 客户端库,基于 PEP 249。
要求 :
MySQL 服务器– 以下之一:
- MySQL >= 5.5
- MariaDB >= 5.5
安装 :
这个模块没有内置在Python中。您必须在外部安装它。要安装此类型,请在终端中输入以下命令。
pip install PyMySQL
连接到 MySQL
获取此类实例的正确方法是调用connect()方法。此方法建立与 MySQL 数据库的连接并接受几个参数:
Parameters :
- host – Host where the database server is located
- user – Username to log in as
- password – Password to use.
- database – Database to use, None to not use a particular one.
- port – MySQL port to use, default is usually OK. (default: 3306)
示例 1:让我们连接到 MySQL 服务器。
Python3
import pymysql
def mysqlconnect():
# To connect MySQL database
conn = pymysql.connect(
host='localhost',
user='root',
password = "pass",
db='College',
)
cur = conn.cursor()
cur.execute("select @@version")
output = cur.fetchall()
print(output)
# To close the connection
conn.close()
# Driver Code
if __name__ == "__main__" :
mysqlconnect()
Python3
import pymysql
def mysqlconnect():
# To connect MySQL database
conn = pymysql.connect(
host='localhost',
user='root',
password = "pass",
db='College',
)
cur = conn.cursor()
# Select query
cur.execute("select * from STUDENT")
output = cur.fetchall()
for i in output:
print(i)
# To close the connection
conn.close()
# Driver Code
if __name__ == "__main__" :
mysqlconnect()
输出 :
(('5.7.30-0ubuntu0.18.04.1',),)
示例 2:让我们尝试从数据库中访问一个表
使用的表:
Python3
import pymysql
def mysqlconnect():
# To connect MySQL database
conn = pymysql.connect(
host='localhost',
user='root',
password = "pass",
db='College',
)
cur = conn.cursor()
# Select query
cur.execute("select * from STUDENT")
output = cur.fetchall()
for i in output:
print(i)
# To close the connection
conn.close()
# Driver Code
if __name__ == "__main__" :
mysqlconnect()
输出: