首页  >  文章  >  数据库  >  Python 中的 MySqldb 连接

Python 中的 MySqldb 连接

WBOY
WBOY转载
2023-09-22 21:13:17996浏览

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 连接的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除