使用PyMySQL模块的Python-MySQL连接

本教程介绍如何使用名为PyMySQL的python连接器模块将python应用程序与MySQL服务器和MySQL数据库连接起来,该模块有一个Github页面,可以通过以下链接访问:https://github.com/PyMySQL/PyMySQL

在本教程中,假设您对MySQL有一定的了解,并且已经安装了MySQL服务器并创建了数据库。本教程使用已安装MySQL的XAMPP。

PyMySQL是一个纯python MySQL客户端库。它可以通过一个简单的命令安装:

pip install pymysql

之后,您现在可以导入库并建立类似于此程序的连接

import pymysql
# Creation of PyMySQL Connection Object
conn = pymysql.connect(host="localhost",port=3306,db="mydb",user="root",password="")
print("Connection established sucessfully")
conn.close() # You always have to close the connection

SQL Server和应用程序之间的连接通常需要这两件事

1、连接对象的创建

2、光标对象的创建

连接对象将用于通过参数在应用程序和SQL Server之间建立连接,这些参数大多数情况下是:主机(如本地主机或其他ip地址)、端口(如3306)、数据库(目标数据库名称)、用户名(您注册的SQL用户名)、密码(如有)。

然后,您现在可以创建一个Cursor对象,从中可以使用.execute()方法或.exec()for Java执行SQL命令。

下面的示例显示了如何从MySQL数据库中检索值

import pymysql
# Connection
conn = pymysql.connect(host="localhost",port=3306,db="mydb",user="root",password="")
print("Connection established sucessfully")
# Creation of a Cursor object
cursor = conn.cursor()
# Storing SQL Statements in a variable sql
sql = "SELECT * FROM students"
# Calling execute method
cursor.execute(sql)
# storing results in a result variable
result = cursor.fetchall() # fetchall retrieves all records
# Display the values
print(result) 
# Close the connection
cursor.close()
conn.close()

该库可用于为Python程序/应用程序创建CRUD(创建、读取、更新、删除)功能。它甚至可以执行存储过程和处理事务。

本例中使用的程序可在my Github gists页面上找到:https://gist.github.com/roycechua23/bda8f008c8e8552d31880a2bd789dd18这里还有一些例子,可以使用Python更新/删除/插入记录,并实现您自己的SQLController类,以避免冗余地建立连接。

猜你喜欢

转载自blog.csdn.net/zhishifufei/article/details/127780459