Python-MySQL-选择数据

时间:2020-02-23 14:43:03  来源:igfitidea点击:

在本教程中,我们将学习使用Python从MySQL数据库中选择数据。

前提条件

要理解本教程,您需要具备一些MySQL的先验知识。

在本教程中,我们将使用"员工"表。

该表已经有一些行,如下所示。

mysql< SELECT * FROM employee;
+------------+-----------+----------+---------------------+
| employeeid | firstname | lastname | created_at          |
+------------+-----------+----------+---------------------+
| e01        | John      | Doe      | 2016-01-01 10:20:30 |
| e02        | Jane      | Doe      | 2016-01-01 12:13:14 |
| e03        | Peter     | Parker   | 2016-01-02 15:16:17 |
| e04        | Bruce     | Banner   | 2016-01-03 10:20:30 |
| e05        | Bruce     | Wayne    | 2016-01-04 12:00:00 |
| e06        | Tony      | Stark    | 2016-01-05 12:13:14 |
| e07        | Doctor    | Strange  | 2016-01-05 13:14:15 |
| e08        | Doctor    | Who      | 2016-01-05 13:14:15 |
+------------+-----------+----------+---------------------+
8 rows in set (0.00 sec)

从表中选择数据

要从表中选择数据,我们需要执行以下步骤。

  • 使用mysql.connector.connect()方法连接到MySQL服务器。

  • 从步骤1中创建的连接中获取MySQL游标。

  • 使用游标执行SELECT查询。

  • 从结果集中获取日期。

  • 紧密连接。

数据获取方法

要获取数据,我们可以使用以下方法。

  • fetchone()方法将从结果集中一次获取一行。

  • fetchall()方法将立即从结果集中获取所有行。

fetchone()方法

要一次获取一行,我们使用fetchone()方法。

在下面的Python程序中,我们一次获取一行。

# import module
import mysql.connector

# import errorcode
from mysql.connector import errorcode

# get db connection
try:

    cnx = mysql.connector.connect(
        user='theitroadtheitroad',
        password='',
        host='127.0.0.1',
        database='mydb'
    )

except mysql.connector.Error as err:
    
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Invalid credential. Unable to access database.')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exists')
    else:
        print('Failed to connect to database')

# now fetch data
try:
    # cursor
    cnxCursor = cnx.cursor()
    
    # sql query
    query = "SELECT * FROM employee"
    
    # execute
    cnxCursor.execute(query)
    
    # fetch
    row = cnxCursor.fetchone()
    
    # loop
    while row is not None:
        # print result
        print(row)
        
        # fetch another row
        row = cnxCursor.fetchone()
    
except mysql.connector.Error as err:
    
    print("Error:", err.message)
    
    # close connection
    cnx.close()

except:

    print("Unknown error occurred!")

    # close connection
    cnx.close()

finally:
    # close cursor
    cnxCursor.close()
    # close connection
    cnx.close()

上面的代码将为我们提供类似的输出。

(u'e01', u'John', u'Doe', datetime.datetime(2016, 1, 1, 10, 20, 30))
(u'e02', u'Jane', u'Doe', datetime.datetime(2016, 1, 1, 12, 13, 14))
(u'e03', u'Peter', u'Parker', datetime.datetime(2016, 1, 2, 15, 16, 17))
(u'e04', u'Bruce', u'Banner', datetime.datetime(2016, 1, 3, 10, 20, 30))
(u'e05', u'Bruce', u'Wayne', datetime.datetime(2016, 1, 4, 12, 0))
(u'e06', u'Tony', u'Stark', datetime.datetime(2016, 1, 5, 12, 13, 14))
(u'e07', u'Doctor', u'Strange', datetime.datetime(2016, 1, 5, 13, 14, 15))
(u'e08', u'Doctor', u'Who', datetime.datetime(2016, 1, 5, 13, 14, 15))

fetchall()方法

要从表中选择所有行,我们使用fetchall()方法。

在下面的Python程序中,我们将从表中获取所有行。

# import module
import mysql.connector

# import errorcode
from mysql.connector import errorcode

# get db connection
try:

    cnx = mysql.connector.connect(
        user='theitroadtheitroad',
        password='',
        host='127.0.0.1',
        database='mydb'
    )

except mysql.connector.Error as err:
    
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Invalid credential. Unable to access database.')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exists')
    else:
        print('Failed to connect to database')

# now fetch data
try:
    # cursor
    cnxCursor = cnx.cursor()
    
    # sql query
    query = "SELECT * FROM employee"
    
    # execute
    cnxCursor.execute(query)
    
    # result
    result = cnxCursor.fetchall()
    
    # print result
    print('Total rows: %d' % cnxCursor.rowcount)
    for row in result:
        print(row)
    
except mysql.connector.Error as err:
    
    print("Error:", err.message)
    
    # close connection
    cnx.close()

except:

    print("Unknown error occurred!")

    # close connection
    cnx.close()

finally:
    # close cursor
    cnxCursor.close()
    # close connection
    cnx.close()

上面的代码将打印以下输出。

Total rows: 8
(u'e01', u'John', u'Doe', datetime.datetime(2016, 1, 1, 10, 20, 30))
(u'e02', u'Jane', u'Doe', datetime.datetime(2016, 1, 1, 12, 13, 14))
(u'e03', u'Peter', u'Parker', datetime.datetime(2016, 1, 2, 15, 16, 17))
(u'e04', u'Bruce', u'Banner', datetime.datetime(2016, 1, 3, 10, 20, 30))
(u'e05', u'Bruce', u'Wayne', datetime.datetime(2016, 1, 4, 12, 0))
(u'e06', u'Tony', u'Stark', datetime.datetime(2016, 1, 5, 12, 13, 14))
(u'e07', u'Doctor', u'Strange', datetime.datetime(2016, 1, 5, 13, 14, 15))
(u'e08', u'Doctor', u'Who', datetime.datetime(2016, 1, 5, 13, 14, 15))