
Mysql 是使用最广泛的开源数据库之一。 Python 提供了连接到该数据库并使用该数据库存储和检索数据的方法。
安装 pymysql
根据您使用的 python 环境,pymysql 包可以是使用以下方法之一安装。
# From python console pip install pymysql #Using Anaconda conda install -c anaconda pymysql # Add modules using any python IDE pymysql
连接MySql
现在我们可以使用以下代码连接Mysql环境。连接后我们正在查找数据库的版本。
示例
import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()输出
运行上面的代码给我们以下结果 -
立即学习“Python免费学习笔记(深入)”;
婚纱影楼小程序提供了一个连接用户与影楼的平台,相当于影楼在微信的官网。它能帮助影楼展示拍摄实力,记录访客数据,宣传优惠活动。使用频率高,方便传播,是影楼在微信端宣传营销的得力助手。功能特点:样片页是影楼展示优秀摄影样片提供给用户欣赏并且吸引客户的。套系页是影楼根据市场需求推出的不同套餐,用户可以按照自己的喜好预定套系。个人中心可以查看用户预约的拍摄计划,也可以获取到影楼的联系方式。
Database version : 8.0.19
执行数据库命令
为了执行数据库命令,我们创建一个数据库游标和一个要传递到该游标的 Sql 查询。然后我们使用cursor.execute方法来获取游标执行的结果。
示例
import pymysql
# Open database connection
db = pymysql.connect("localhost","username","paswd","DBname" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()输出
运行上面的代码给我们以下结果 -
立即学习“Python免费学习笔记(深入)”;
fname = Jack, lname = Ma, age = 31, sex = M, income = 12000










