安装 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 连接的详细内容。
