Python 中的 MySqldb 连接

ID:1585 / 打印

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天24分享网给大家整理了《Python 中的 MySqldb 连接》,聊聊,我们一起来看看吧!

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()

输出

运行上面的代码给我们以下结果 -

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()

输出

运行上面的代码给我们以下结果 -

fname = Jack, lname = Ma, age = 31, sex = M, income = 12000

今天关于《Python 中的 MySqldb 连接》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注the24.cn!

上一篇: MySQL的主要支持者
下一篇: 如果我跳过第四个和第五个参数,即分隔符和位数,MySQL EXPORT_SET() 函数的输出会发生什么?

作者:admin @ 24资源网   2024-09-04

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。