您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python 中的 MySqldb 连接

2025/9/10 4:58:35发布15次查看
mysql 是使用最广泛的开源数据库之一。 python 提供了连接到该数据库并使用该数据库存储和检索数据的方法。
安装 pymysql根据您使用的 python 环境,pymysql 包可以是使用以下方法之一安装。
# from python consolepip install pymysql#using anacondaconda install -c anaconda pymysql# add modules using any python idepymysql
连接mysql现在我们可以使用以下代码连接mysql环境。连接后我们正在查找数据库的版本。
示例import pymysql# open database connectiondb = pymysql.connect("localhost","testuser","test123","testdb" )# prepare a cursor object using cursor() methodcursor = 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 serverdb.close()
输出运行上面的代码给我们以下结果 -
database version : 8.0.19
执行数据库命令为了执行数据库命令,我们创建一个数据库游标和一个要传递到该游标的 sql 查询。然后我们使用cursor.execute方法来获取游标执行的结果。
示例import pymysql# open database connectiondb = pymysql.connect("localhost","username","paswd","dbname" )# prepare a cursor object using cursor() methodcursor = 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 serverdb.close()
输出运行上面的代码给我们以下结果 -
fname = jack, lname = ma, age = 31, sex = m, income = 12000
以上就是python 中的 mysqldb 连接的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product