Python MySQL如何使用select查询?代码示例

2021年3月30日10:14:21 发表评论 1,291 次浏览

Python数据库API(应用程序接口)是标准Python的数据库接口。大多数Python数据库接口都遵守该标准。 Python数据库支持各种数据库服务器, 例如MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase等。要从Python与MySQL数据库服务器连接, 我们需要导入mysql.connector模块。

下面是一个与MySQL数据库连接的程序极客.

# importing required library 
import mysql.connector
  
# connecting to the database 
dataBase = mysql.connector.connect(
                      host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" ) 
  
# preparing a cursor object 
cursorObject = dataBase.cursor() 
  
# disconnecting from server
dataBase.close()

上面的程序说明了与MySQL数据库的连接极客其中主机名是本地主机, 用户名是用户密码是pswrd.

SELECT查询

在MySQL中连接数据库后, 我们可以从其中的表中SELECT查询。

语法如下:

为了从表中选择特定的属性列, 我们编写属性名称。

SELECT attr1, attr2 FROM table_name

为了从表格中选择所有属性列, 我们使用星号" *"。

SELECT * FROM table_name

示例1:让我们考虑一下表格如下所示–

python-mysql-select

下面是一个从数据库表中选择查询的程序。

# importing required library 
import mysql.connector 
    
# connecting to the database 
dataBase = mysql.connector.connect(
                      host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" ) 
    
# preparing a cursor object 
cursorObject = dataBase.cursor()
    
print ( "Displaying NAME and ROLL columns from the STUDENT table:" )
  
# selecting query
query = "SELECT NAME, ROLL FROM STUDENT"
cursorObject.execute(query)
  
myresult = cursorObject.fetchall()
  
for x in myresult:
     print (x)
  
# disconnecting from server
dataBase.close()

输出如下:

python-mysql-select-2

示例2:让我们看另一个在表中选择查询的示例。

# importing required library 
import mysql.connector 
    
# connecting to the database 
dataBase = mysql.connector.connect(
                      host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" )  
    
# preparing a cursor object 
cursorObject = dataBase.cursor()
    
print ( "Displaying NAME and ROLL columns from the STUDENT table:" )
  
# selecting query
query = "SELECT * FROM STUDENT"
cursorObject.execute(query)
  
myresult = cursorObject.fetchall()
  
for x in myresult:
     print (x)
  
# disconnecting from server
dataBase.close()

输出如下:

python-mysql-select-3

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: