Python 数据访问 - 快速指南


Python MySQL - 简介

数据库接口的 Python 标准是 Python DB-API。大多数 Python 数据库接口都遵循此标准。

您可以为您的应用程序选择正确的数据库。Python 数据库 API 支持广泛的数据库服务器,例如 -

  • 数据库管理
  • MySQL
  • PostgreSQL
  • 微软SQL服务器2000
  • 信息系统
  • 英特贝斯
  • 甲骨文
  • 赛贝斯

以下是可用的 Python 数据库接口的列表:Python 数据库接口和 API。您必须为需要访问的每个数据库下载单独的 DB API 模块。例如,如果您需要访问 Oracle 数据库以及 MySQL 数据库,则必须同时下载 Oracle 和 MySQL 数据库模块。

什么是 mysql-connector-python?

MySQL Python/Connector 是一个用于从 Python 连接到 MySQL 数据库服务器的接口。它实现了 Python 数据库 API,并构建在 MySQL 之上。

如何安装 mysql-connector-python?

首先,你需要确保你的机器上已经安装了python。为此,请打开命令提示符并在其中键入 python,然后按 Enter。如果您的系统中已经安装了 python,此命令将显示其版本,如下所示 -

C:\Users\Tutorialspoint>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

现在按ctrl+z,然后按 Enter 键退出 python shell 并创建一个名为 Python_MySQL 的文件夹(您打算在其中安装 Python-MySQL 连接器):

>>> ^Z
C:\Users\Tutorialspoint>d:
D:\>mkdir Python_MySQL

验证画中画

PIP 是 python 中的包管理器,您可以使用它在 Python 中安装各种模块/包。因此,要安装 Mysql-python mysql-connector-python,您需要确保您的计算机中安装了 PIP 并将其位置添加到路径中。

您可以通过执行 pip 命令来执行此操作。如果您的系统中没有 PIP,或者尚未在Path环境变量中添加其位置,您将收到一条错误消息:

D:\Python_MySQL>pip
'pip' is not recognized as an internal or external command,
operable program or batch file.

要安装 PIP,请将get-pip.py下载到上面创建的文件夹,然后从命令导航它并安装 pip,如下所示 -

D:\>cd Python_MySQL
D:\Python_MySQL>python get-pip.py
Collecting pip
Downloading https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl (1.4MB)
|████████████████████████████████| 1.4MB 1.3MB/s
Collecting wheel
Downloading https://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl
Installing collected packages: pip, wheel
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-19.2.2 wheel-0.33.6

安装 mysql-connector-python

安装 Python 和 PIP 后,打开命令提示符并升级 pip(可选),如下所示 -

C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
Using cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Python Data Access
4
Installing collected packages: pip
Found existing installation: pip 19.0.3
Uninstalling pip-19.0.3:
Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2

然后在管理模式下打开命令提示符并安装 python MySQL connect 作为 -

C:\WINDOWS\system32>pip install mysql-connector-python
Collecting mysql-connector-python
Using cached https://files.pythonhosted.org/packages/99/74/f41182e6b7aadc62b038b6939dce784b7f9ec4f89e2ae14f9ba8190dc9ab/mysql_connector_python-8.0.17-py2.py3-none-any.whl
Collecting protobuf>=3.0.0 (from mysql-connector-python)
Using cached https://files.pythonhosted.org/packages/09/0e/614766ea191e649216b87d331a4179338c623e08c0cca291bcf8638730ce/protobuf-3.9.1-cp37-cp37m-win32.whl
Collecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python)
Using cached https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools in c:\program files (x86)\python37-32\lib\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)
Installing collected packages: six, protobuf, mysql-connector-python
Successfully installed mysql-connector-python-8.0.17 protobuf-3.9.1 six-1.12.0

确认

要验证安装,请创建一个示例 python 脚本,其中包含以下行。

import mysql.connector

如果安装成功,当您执行它时,您不应该收到任何错误 -

D:\Python_MySQL>python test.py
D:\Python_MySQL>

从头开始安装 python

简单来说,如果您需要从头开始安装Python。访问Python 主页

安装Python

单击“下载”按钮,您将被重定向到下载页面,该页面提供了适用于各种平台的最新版本 python 的链接,选择一个并下载。

Python 下载

例如,我们下载了 python-3.7.4.exe(适用于 Windows)。双击下载的.exe文件开始安装过程。

开始安装

选中“将 Python 3.7 添加到路径”选项并继续安装。完成此过程后,python 将安装在您的系统中。

安装后

Python MySQL - 数据库连接

要连接 MySQL,(一种方法是)在系统中打开 MySQL 命令提示符,如下所示 -

MySQL 命令提示符

这里要求输入密码;您需要输入安装时为默认用户(root)设置的密码。

然后与 MySQL 建立连接,显示以下消息 -

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

您可以随时在 mysql> 提示符下使用 exit 命令断开与 MySQL 数据库的连接。

mysql> exit
Bye

使用python与MySQL建立连接

在使用 python 建立与 MySQL 数据库的连接之前,假设 -

  • 我们已经创建了一个名为 mydb 的数据库。

  • 我们创建了一个表 EMPLOYEE,其中包含 FIRST_NAME、LAST_NAME、AGE、SEX 和 INCOME 列。

  • 我们用来连接 MySQL 的凭据是用户名:root,密码:password

您可以使用connect()构造函数建立连接。它接受用户名、密码、主机和需要连接的数据库名称(可选),并返回 MySQLConnection 类的对象。

例子

以下是连接 MySQL 数据库“mydb”的示例。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("SELECT DATABASE()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()

输出

执行时,该脚本会产生以下输出 -

D:\Python_MySQL>python EstablishCon.py
Connection established to: ('mydb',)

您还可以通过将凭据(用户名、密码、主机名和数据库名称)传递给connection.MySQLConnection()来建立与 MySQL 的连接,如下所示 -

from mysql.connector import (connection)

#establishing the connection
conn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb')

#Closing the connection
conn.close()

Python MySQL - 创建数据库

您可以使用 CREATE DATABASE 查询在 MYSQL 中创建数据库。

句法

以下是 CREATE DATABASE 查询的语法 -

CREATE DATABASE name_of_the_database

例子

以下语句在 MySQL 中创建一个名为 mydb 的数据库 -

mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.04 sec)

如果您使用 SHOW DATABASES 语句观察数据库列表,您可以观察其中新创建的数据库,如下所示 -

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| logging            |
| mydatabase         |
| mydb               |
| performance_schema |
| students           |
| sys                |
+--------------------+
26 rows in set (0.15 sec)

使用 python 在 MySQL 中创建数据库

与MySQL建立连接后,要操作其中的数据,您需要连接到数据库。您可以连接到现有数据库,也可以创建自己的数据库。

您需要特殊权限才能创建或删除 MySQL 数据库。因此,如果您有权访问 root 用户,则可以创建任何数据库。

例子

以下示例与 MYSQL 建立连接并在其中创建数据库。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping database MYDATABASE if already exists.
cursor.execute("DROP database IF EXISTS MyDatabase")

#Preparing query to create a database
sql = "CREATE database MYDATABASE";

#Creating a database
cursor.execute(sql)

#Retrieving the list of databases
print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

List of databases:
[('information_schema',), ('dbbug61332',), ('details',), ('exampledatabase',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',)]

Python MySQL - 创建表

CREATE TABLE 语句用于在 MYSQL 数据库中创建表。在这里,您需要指定表的名称以及每列的定义(名称和数据类型)。

句法

以下是在 MySQL 中创建表的语法 -

CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

例子

以下查询在 MySQL 中创建一个名为 EMPLOYEE 的表,其中包含五列,即 FIRST_NAME、LAST_NAME、AGE、SEX 和 INCOME。

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.42 sec)

DESC 语句给出指定表的描述。使用它,您可以验证表是否已创建,如下所示 -

mysql> Desc Employee;
+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| FIRST_NAME | char(20) | NO   |     | NULL    |       |
| LAST_NAME  | char(20) | YES  |     | NULL    |       |
| AGE        | int(11)  | YES  |     | NULL    |       |
| SEX        | char(1)  | YES  |     | NULL    |       |
| INCOME     | float    | YES  |     | NULL    |       |
+------------+----------+------+-----+---------+-------+
5 rows in set (0.07 sec)

使用 python 在 MySQL 中创建表

名为execute()的方法(在游标对象上调用)接受两个变量 -

  • 表示要执行的查询的字符串值。

  • 可选的 args 参数,可以是元组或列表或字典,表示查询的参数(占位符的值)。

它返回一个整数值,表示受查询影响的行数。

建立数据库连接后,您可以通过将 CREATE TABLE 查询传递给execute()方法来创建表。

简而言之,使用 python 7minus 创建表;

  • 导入mysql.connector包。

  • 使用mysql.connector.connect()方法创建一个连接对象,将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。

  • 通过对上面创建的连接对象调用cursor()方法来创建游标对象。

  • 然后,通过将CREATE TABLE语句作为参数传递给execute()方法来执行该语句。

例子

以下示例在数据库 mydb 中创建一个名为Employee的表。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Dropping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)'''
cursor.execute(sql)

#Closing the connection
conn.close()

Python MySQL - 插入数据

您可以使用INSERT INTO语句向 MySQL 的现有表添加新行。在此,您需要指定表名、列名和值(与列名的顺序相同)。

句法

以下是MySQL的INSERT INTO语句的语法。

INSERT INTO TABLE_NAME (column1, column2,column3,...columnN)
VALUES (value1, value2, value3,...valueN);

例子

以下查询将一条记录插入名为 EMPLOYEE 的表中。

INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('
   Mac', 'Mohan', 20, 'M', 2000
);

您可以在插入操作后使用 SELECT 语句验证表的记录:

mysql> select * from Employee;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Mac        | Mohan     | 20   | M    | 2000   | 
+------------+-----------+------+------+--------+
1 row in set (0.00 sec)

并不强制指定列名,如果您以与表列相同的顺序传递记录的值,则可以执行不带列名的 SELECT 语句,如下所示 -

INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000);

使用python向MySQL表中插入数据

execute ()方法(在游标对象上调用)接受查询作为参数并执行给定的查询。要插入数据,需要将 MySQL INSERT 语句作为参数传递给它。

cursor.execute("""INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Mac', 'Mohan', 20, 'M', 2000)""")

使用 python 将数据插入 MySQL 的表中 -

  • 导入mysql.connector包。

  • 使用mysql.connector.connect()方法创建一个连接对象,将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。

  • 通过在上面创建的连接对象上调用cursor ()方法来创建游标对象

  • 然后,通过将INSERT语句作为参数传递给execute()方法来执行该语句。

例子

以下示例执行 SQL INSERT 语句以将记录插入 EMPLOYEE 表 -

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

# Preparing SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(
   FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
   VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""

try:
   # Executing the SQL command
   cursor.execute(sql)

   # Commit your changes in the database
   conn.commit()

except:
   # Rolling back in case of error
   conn.rollback()

# Closing the connection
conn.close()

动态插入值

您还可以使用“%s”代替MySQL 的INSERT查询中的值,并将值作为列表传递给它们,如下所示 -

cursor.execute("""INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000)""", 
   ('Ramya', 'Ramapriya', 25, 'F', 5000))

例子

以下示例动态地将记录插入到 Employee 表中。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

# Preparing SQL query to INSERT a record into the database.
insert_stmt = (
   "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)"
   "VALUES (%s, %s, %s, %s, %s)"
)
data = ('Ramya', 'Ramapriya', 25, 'F', 5000)

try:
   # Executing the SQL command
   cursor.execute(insert_stmt, data)
   
   # Commit your changes in the database
   conn.commit()

except:
   # Rolling back in case of error
   conn.rollback()

print("Data inserted")

# Closing the connection
conn.close()

输出

Data inserted

Python MySQL - 选择数据

您可以使用 SELECT 查询从 MySQL 中的表中检索/获取数据。该查询/语句以表格形式返回指定表的内容,称为结果集。

句法

以下是 SELECT 查询的语法 -

SELECT column1, column2, columnN FROM table_name;

例子

假设我们在 MySQL 中创建了一个名为 cricketers_data 的表:

CREATE TABLE cricketers_data(
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255)
);

如果我们使用 INSERT 语句插入 5 条记录:

insert into cricketers_data values(
   'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into cricketers_data values(
   'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into cricketers_data values(
   'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into cricketers_data values(
   'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into cricketers_data values(
   'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');

以下查询从表中检索 FIRST_NAME 和 Country 值。

mysql> select FIRST_NAME, Country from cricketers_data;
+------------+-------------+
| FIRST_NAME | Country     |
+------------+-------------+
| Shikhar    | India       |
| Jonathan   | SouthAfrica |
| Kumara     | Srilanka    |
| Virat      | India       |
| Rohit      | India       |
+------------+-------------+
5 rows in set (0.00 sec)

您还可以使用 * 检索每条记录的所有值,将列名设置为 -

mysql> SELECT * from cricketers_data;
+------------+------------+---------------+----------------+-------------+
| First_Name | Last_Name  | Date_Of_Birth | Place_Of_Birth | Country     |
+------------+------------+---------------+----------------+-------------+
| Shikhar    | Dhawan     | 1981-12-05    | Delhi          | India       |
| Jonathan   | Trott      | 1981-04-22    | CapeTown       | SouthAfrica |
| Kumara     | Sangakkara | 1977-10-27    | Matale         | Srilanka    |
| Virat      | Kohli      | 1988-11-05    | Delhi          | India       |
| Rohit      | Sharma     | 1987-04-30    | Nagpur         | India       |
+------------+------------+---------------+----------------+-------------+
5 rows in set (0.00 sec)

使用Python从MYSQL表中读取数据

READ 对任何数据库的操作意味着从数据库中获取一些有用的信息。您可以使用mysql-connector-python 提供的fetch()方法从 MYSQL 获取数据。

Cursor.MySQLCursor类提供了三种方法,即fetchall()、fetchmany()fetchone() 其中,

  • fetchall ()方法检索查询结果集中的所有行并将它们作为元组列表返回。(如果我们在检索几行后执行此操作,它将返回剩余的行)。

  • fetchone ()方法获取查询结果中的下一行并将其作为元组返回。

  • fetchmany ()方法与 fetchone() 类似,但它检索查询结果集中的下一组行,而不是单个行。

- 结果集是使用游标对象查询表时返回的对象。

rowcount - 这是一个只读属性,返回受execute() 方法影响的行数。

例子

以下示例使用 SELECT 查询获取 EMPLOYEE 表的所有行,并从最初获得的结果集中,我们使用 fetchone() 方法检索第一行,然后使用 fetchall() 方法获取其余行。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE'''

#Executing the query
cursor.execute(sql)

#Fetching 1st row from the table
result = cursor.fetchone();
print(result)

#Fetching 1st row from the table
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()

输出

('Krishna', 'Sharma', 19, 'M', 2000.0)
[('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)]

以下示例使用 fetchmany() 方法检索 EMPLOYEE 表的前两行。

例子

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE'''

#Executing the query
cursor.execute(sql)

#Fetching 1st row from the table
result = cursor.fetchmany(size =2);
print(result)

#Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

Python MySQL -Where 子句

如果要获取、删除或更新 MySQL 中表的特定行,则需要使用 where 子句指定条件来过滤操作的表的行。

例如,如果您有一个带有 where 子句的 SELECT 语句,则只会检索满足指定条件的行。

句法

以下是 WHERE 子句的语法 -

SELECT column1, column2, columnN
FROM table_name
WHERE [condition]

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句插入 4 条记录:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

以下MySQL语句检索收入大于4000的员工的记录。

mysql> SELECT * FROM EMPLOYEE WHERE INCOME > 4000;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Raj        | Kandukuri | 20   | M    | 7000   |
| Ramya      | Ramapriya | 25   | F    | 5000   |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)

使用 python 的 WHERE 子句

使用 python 程序从表中获取特定记录 -

  • 导入mysql.connector包。

  • 使用mysql.connector.connect()方法创建一个连接对象,将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。

  • 通过对上面创建的连接对象调用cursor()方法来创建游标对象。

  • 然后,通过将WHERE子句作为参数传递给execute()方法来执行带有 WHERE 子句的 SELECT语句。

例子

以下示例创建一个名为 Employee 的表并填充它。然后使用 where 子句检索年龄值小于 23 的记录。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = '''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)'''
cursor.execute(sql)

#Populating the table
insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES (%s, %s, %s, %s, %s)"

data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000),
('Ramya', 'Ramapriya', 25, 'F', 5000),('Mac', 'Mohan', 26, 'M', 2000)]
cursor.executemany(insert_stmt, data)
conn.commit()

#Retrieving specific records using the where clause
cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

Python MySQL - 排序依据

使用 SELECT 查询获取数据时,您可以使用 OrderBy 子句按所需顺序(升序或降序)对结果进行排序。默认情况下,该子句按升序对结果进行排序,如果需要按降序排列,则需要显式使用“DESC”。

句法

以下是 SELECT 列列表的语法

FROM table_name
[WHERE condition]
[ORDER BY column1, column2,.. columnN] [ASC | DESC]; of the ORDER BY clause:

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句插入 4 条记录:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

以下语句按年龄升序检索 EMPLOYEE 表的内容。

mysql> SELECT * FROM EMPLOYEE ORDER BY AGE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    |   19 |    M |   2000 |
| Raj        | Kandukuri |   20 |    M |   7000 |
| Ramya      | Ramapriya |   25 |    F |   5000 |
| Mac        | Mohan     |   26 |    M |   2000 |
+------------+-----------+------+------+--------+
4 rows in set (0.04 sec)

您还可以使用 DESC 按降序检索数据:

mysql> SELECT * FROM EMPLOYEE ORDER BY FIRST_NAME, INCOME DESC;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    |   19 |    M |   2000 |
| Mac        | Mohan     |   26 |    M |   2000 |
| Raj        | Kandukuri |   20 |    M |   7000 |
| Ramya      | Ramapriya |   25 |    F |   5000 |
+------------+-----------+------+------+--------+
4 rows in set (0.00 sec)

使用 python 的 ORDER BY 子句

要按特定顺序检索表的内容,请对游标对象调用execute()方法,并将SELECT 语句和ORDER BY 子句作为参数传递给它。

例子

在下面的示例中,我们将创建一个包含 name 和 Employee 的表,填充该表,并使用 ORDER BY 子句按年龄(升序)顺序检索其记录。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = '''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)'''
cursor.execute(sql)

#Populating the table
insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES (%s, %s, %s, %s, %s)"

data = [('Krishna', 'Sharma', 26, 'M', 2000), 
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 29, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000)]
cursor.executemany(insert_stmt, data)
conn.commit()

#Retrieving specific records using the ORDER BY clause
cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

[('Raj', 'Kandukuri', 20, 'M', 7000.0), 
   ('Krishna', 'Sharma', 26, 'M', 2000.0), 
   ('Mac', 'Mohan', 26, 'M', 2000.0), 
   ('Ramya', 'Ramapriya', 29, 'F', 5000.0)
]

以同样的方式,您可以使用 ORDER BY 子句按降序从表中检索数据。

例子

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving specific records using the ORDERBY clause
cursor.execute("SELECT * from EMPLOYEE ORDER BY INCOME DESC")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

[('Raj', 'Kandukuri', 20, 'M', 7000.0), 
   ('Ramya', 'Ramapriya', 29, 'F', 5000.0), 
   ('Krishna', 'Sharma', 26, 'M', 2000.0), 
   ('Mac', 'Mohan', 26, 'M', 2000.0)
]

Python MySQL - 更新表

对任何数据库的 UPDATE 操作都会更新数据库中已存在的一条或多条记录。您可以使用 UPDATE 语句更新 MySQL 中现有记录的值。要更新特定行,您需要同时使用 WHERE 子句。

句法

以下是 MySQL 中 UPDATE 语句的语法 -

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

您可以使用 AND 或 OR 运算符组合 N 个条件。

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句插入 4 条记录:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

以下 MySQL 语句将所有男性员工的年龄增加一岁 -

mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0

如果检索表的内容,您可以看到更新后的值如下:

mysql> select * from EMPLOYEE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 20   | M    | 2000   |
| Raj        | Kandukuri | 21   | M    | 7000   |
| Ramya      | Ramapriya | 25   | F    | 5000   |
| Mac        | Mohan     | 27   | M    | 2000   |
+------------+-----------+------+------+--------+
4 rows in set (0.00 sec)

使用 Python 更新表的内容

使用 python 更新 MySQL 表中的记录 -

  • 导入mysql.connector包。

  • 使用mysql.connector.connect()方法创建一个连接对象,将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。

  • 通过对上面创建的连接对象调用cursor()方法来创建游标对象。

  • 然后,通过将 UPDATE 语句作为参数传递给execute()方法来执行它。

例子

以下示例将所有男性的年龄增加一岁。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Preparing the query to update the records
sql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' '''
try:
   # Execute the SQL command
   cursor.execute(sql)
   
   # Commit your changes in the database
   conn.commit()
except:
   # Rollback in case there is any error
   conn.rollback()
   
#Retrieving data
sql = '''SELECT * from EMPLOYEE'''

#Executing the query
cursor.execute(sql)

#Displaying the result
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 22, 'M', 2000.0), 
   ('Raj', 'Kandukuri', 23, 'M', 7000.0), 
   ('Ramya', 'Ramapriya', 26, 'F', 5000.0)
]

Python MySQL - 删除数据

要从 MySQL 表中删除记录,需要使用DELETE FROM语句。要删除特定记录,您需要配合使用 WHERE 子句。

句法

以下是 MYSQL 中 DELETE 查询的语法 -

DELETE FROM table_name [WHERE Clause]

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句插入 4 条记录:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

以下 MySQL 语句删除 FIRST_NAME 为“Mac”的员工记录。

mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac';
Query OK, 1 row affected (0.12 sec)

如果你检索表的内容,你只能看到 3 条记录,因为我们已经删除了 1 条记录。

mysql> select * from EMPLOYEE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 20   | M    | 2000   |
| Raj        | Kandukuri | 21   | M    | 7000   |
| Ramya      | Ramapriya | 25   | F    | 5000   |
+------------+-----------+------+------+--------+
3 rows in set (0.00 sec)

如果执行不带 WHERE 子句的 DELETE 语句,则指定表中的所有记录都将被删除。

mysql> DELETE FROM EMPLOYEE;
Query OK, 3 rows affected (0.09 sec)

如果检索表的内容,您将得到一个空集,如下所示 -

mysql> select * from EMPLOYEE;
Empty set (0.00 sec)

使用python删除表的记录

当您想从数据库中删除某些记录时,需要执行 DELETE 操作。

删除表中的记录 -

  • 导入mysql.connector包。

  • 使用mysql.connector.connect()方法创建一个连接对象,将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。

  • 通过对上面创建的连接对象调用cursor()方法来创建游标对象。

  • 然后,通过将DELETE语句作为参数传递给execute()方法来执行该语句。

例子

以下程序删除年龄超过 20 岁的 EMPLOYEE 的所有记录 -

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
print("Contents of the table: ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())

#Preparing the query to delete records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (25)

try:
   # Execute the SQL command
   cursor.execute(sql)
   
   # Commit your changes in the database
   conn.commit()
except:
   # Roll back in case there is any error
   conn.rollback()

#Retrieving data
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

Contents of the table:
[('Krishna', 'Sharma', 22, 'M', 2000.0), 
   ('Raj', 'Kandukuri', 23, 'M', 7000.0), 
   ('Ramya', 'Ramapriya', 26, 'F', 5000.0), 
   ('Mac', 'Mohan', 20, 'M', 2000.0), 
   ('Ramya', 'Rama priya', 27, 'F', 9000.0)]

Contents of the table after delete operation:
[('Krishna', 'Sharma', 22, 'M', 2000.0), 
   ('Raj', 'Kandukuri', 23, 'M', 7000.0), 
   ('Mac', 'Mohan', 20, 'M', 2000.0)]

Python MySQL - 删除表

您可以使用DROP TABLE语句删除整个表。您只需指定需要删除的表的名称即可。

句法

以下是 MySQL 中 DROP TABLE 语句的语法 -

DROP TABLE table_name;

例子

在删除表之前,使用 SHOW TABLES 语句获取表列表,如下所示 -

mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb  |
+-----------------+
| contact         |
| cricketers_data |
| employee        |
| sample          |
| tutorials       |
+-----------------+
5 rows in set (0.00 sec)

以下语句从数据库中完全删除名为sample的表 -

mysql> DROP TABLE sample;
Query OK, 0 rows affected (0.29 sec)

由于我们已经从MySQL中删除了名为sample的表,因此如果您再次获取表列表,您将在其中找不到表名sample。

mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb  |
+-----------------+
| contact         |
| cricketers_data |
| employee        |
| tutorials       |
+-----------------+
4 rows in set (0.00 sec)

使用 python 删除表

您可以在需要时删除表,使用MYSQL的DROP语句,但是在删除任何现有表时需要非常小心,因为删除表后丢失的数据将无法恢复。

要使用 python 从 MYSQL 数据库中删除表,请调用游标对象上的execute()方法,并将 drop 语句作为参数传递给它。

例子

下表从数据库中删除名为 EMPLOYEE 的表。

import mysql.connector

#establishing the connection conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

#Creating a cursor object using the cursor() method 
cursor = conn.cursor()

#Retrieving the list of tables print("List of tables in the database: ") 
   cursor.execute("SHOW Tables") print(cursor.fetchall())

#Doping EMPLOYEE table if already exists cursor.execute
   ("DROP TABLE EMPLOYEE") print("Table dropped... ")

#Retrieving the list of tables print(
   "List of tables after dropping the EMPLOYEE table: ") 
   cursor.execute("SHOW Tables") print(cursor.fetchall())

#Closing the connection conn.close()

输出

List of tables in the database:
[('employee',), ('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',), ('tutorials',)]

仅当表存在时才删除表

如果您尝试删除数据库中不存在的表,则会出现错误:

mysql.connector.errors.ProgrammingError: 1051 (42S02): 
   Unknown table 'mydb.employee'

您可以通过在删除之前验证表是否存在(将 IF EXISTS 添加到 DELETE 语句)来防止此错误。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving the list of tables
print("List of tables in the database: ")
cursor.execute("SHOW Tables")
print(cursor.fetchall())

#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
print("Table dropped... ")

#Retrieving the list of tables
print("List of tables after dropping the EMPLOYEE table: ")
cursor.execute("SHOW Tables")
print(cursor.fetchall())

#Closing the connection
conn.close()

输出

List of tables in the database:
[('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',),
('tutorials',)]

Python MySQL - 限制

在获取记录时,如果您想限制特定数量的记录,可以使用 MYSQL 的 LIMIT 子句来实现。

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句插入 4 条记录:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

以下 SQL 语句使用 LIMIT 子句检索 Employee 表的前两条记录。

SELECT * FROM EMPLOYEE LIMIT 2;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 19   | M    | 2000   |
| Raj        | Kandukuri | 20   | M    | 7000   |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)

使用 python 的限制子句

如果通过传递 SELECT 查询和 LIMIT 子句来调用游标对象上的execute()方法,则可以检索所需数量的记录。

要使用 python 从 MYSQL 数据库中删除表,请调用游标对象上的execute()方法,并将 drop 语句作为参数传递给它。

例子

以下 python 示例创建并填充名为 EMPLOYEE 的表,并使用 LIMIT 子句获取该表的前两条记录。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2'''

#Executing the query
cursor.execute(sql)

#Fetching the data
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 26, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

带偏移的限制

如果需要限制从第 n 条记录(不是第 1)开始的记录,可以使用 OFFSET 和 LIMIT 来实现。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''

#Executing the query
cursor.execute(sql)

#Fetching the data
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()

输出

[('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Mac', 'Mohan', 26, 'M', 2000.0)]

Python MySQL - 加入

将数据分为两个表后,您可以使用联接从这两个表中获取组合记录。

例子

假设我们创建了一个名为 EMPLOYEE 的表并向其中填充数据,如下所示 -

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT,
   CONTACT INT
);
Query OK, 0 rows affected (0.36 sec)
INSERT INTO Employee VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000, 101), 
   ('Vinay', 'Bhattacharya', 20, 'M', 6000, 102), 
   ('Sharukh', 'Sheik', 25, 'M', 8300, 103), 
   ('Sarmista', 'Sharma', 26, 'F', 10000, 104), 
   ('Trupthi', 'Mishra', 24, 'F', 6000, 105);
Query OK, 5 rows affected (0.08 sec)
Records: 5 Duplicates: 0 Warnings: 0

然后,如果我们创建了另一个表并将其填充为 -

CREATE TABLE CONTACT(
   ID INT NOT NULL,
   EMAIL CHAR(20) NOT NULL,
   PHONE LONG,
   CITY CHAR(20)
);
Query OK, 0 rows affected (0.49 sec)
INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES 
   (101, 'Krishna@mymail.com', 'Hyderabad'), 
   (102, 'Raja@mymail.com', 'Vishakhapatnam'), 
   (103, 'Krishna@mymail.com', 'Pune'), 
   (104, 'Raja@mymail.com', 'Mumbai');
Query OK, 4 rows affected (0.10 sec)
Records: 4 Duplicates: 0 Warnings: 0

以下语句检索组合这两个表中的值的数据 -

mysql> SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID;
+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+
| FIRST_NAME | LAST_NAME    | AGE  | SEX  | INCOME | CONTACT | ID  | EMAIL              | PHONE | CITY           |
+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+
| Ramya      | Rama Priya   | 27   | F    | 9000   | 101     | 101 | Krishna@mymail.com | NULL  | Hyderabad      |
| Vinay      | Bhattacharya | 20   | M    | 6000   | 102     | 102 | Raja@mymail.com    | NULL  | Vishakhapatnam |
| Sharukh    | Sheik        | 25   | M    | 8300   | 103     | 103 | Krishna@mymail.com | NULL  | Pune           |
| Sarmista   | Sharma       | 26   | F    | 10000  | 104     | 104 | Raja@mymail.com    | NULL  | Mumbai         |
+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+
4 rows in set (0.00 sec)

使用 python 进行 MYSQL JOIN

以下示例从上述两个表中检索由 EMPLOYEE 表的联系人列和 CONTACT 表的 ID 列组合而成的数据。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID'''

#Executing the query
cursor.execute(sql)

#Fetching 1st row from the table
result = cursor.fetchall();
print(result)

#Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 26, 'M', 2000, 101, 101, 'Krishna@mymail.com', 9848022338, 'Hyderabad'), 
   ('Raj', 'Kandukuri', 20, 'M', 7000, 102, 102, 'Raja@mymail.com', 9848022339, 'Vishakhapatnam'), 
   ('Ramya', 'Ramapriya', 29, 'F', 5000, 103, 103, 'Krishna@mymail.com', 9848022337, 'Pune'), 
   ('Mac', 'Mohan', 26, 'M', 2000, 104, 104, 'Raja@mymail.com', 9848022330, 'Mumbai')]

Python MySQL - 游标对象

mysql-connector-python(和类似库)的 MySQLCursor 用于执行与 MySQL 数据库通信的语句。

使用它的方法,您可以执行 SQL 语句、从结果集中获取数据、调用过程。

您可以使用Connection对象/类的cursor()方法创建Cursor对象。

例子

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

方法

以下是 Cursor 类/对象提供的各种方法。

先生编号 方法及说明
1

调用过程()

该方法用于调用现有的MySQL数据库程序。

2

关闭()

该方法用于关闭当前光标对象。

3

信息()

此方法提供有关上次查询的信息。

4

执行许多()

该方法接受一系列参数列表。准备 MySQL 查询并使用所有参数执行它。

5

执行()

此方法接受 MySQL 查询作为参数并执行给定的查询。

6

获取全部()

此方法检索查询结果集中的所有行并将它们作为元组列表返回。(如果我们在检索几行后执行此操作,它将返回剩余的行)

7

fetchone()

此方法获取查询结果中的下一行并将其作为元组返回。

8

fetchmany()

此方法与 fetchone() 类似,但它检索查询结果集中的下一组行,而不是单个行。

9

蚀刻警告()

此方法返回上次执行的查询生成的警告。

特性

以下是 Cursor 类的属性 -

先生编号 属性及描述
1

列名

这是一个只读属性,它返回包含结果集的列名的列表。

2

描述

这是一个只读属性,它返回包含结果集中列的描述的列表。

3

拉斯特罗维德

这是一个只读属性,如果表中有任何自动递增列,则返回上次 INSERT 或 UPDATE 操作中为该列生成的值。

4

行数

这将返回 SELECT 和 UPDATE 操作时返回/更新的行数。

5

陈述

该属性返回最后执行的语句。

Python PostgreSQL - 简介

安装

PostgreSQL 是一个功能强大的开源对象关系数据库系统。它经过超过 15 年的积极开发阶段和经过验证的架构,为其在可靠性、数据完整性和正确性方面赢得了良好的声誉。

要使用 Python 与 PostgreSQL 通信,您需要安装 psycopg,这是一个为 python 编程提供的适配器,当前版本是psycog2

psycopg2 的编写目标是非常小、速度快、稳定如磐石。它可以在 PIP(Python 的包管理器)下使用

使用 PIP 安装 Psycog2

首先,确保您的系统中正确安装了 python 和 PIP,并且 PIP 是最新的。

要升级 PIP,请打开命令提示符并执行以下命令 -

C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
Using cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 19.0.3
Uninstalling pip-19.0.3:
Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2

然后,在管理模式下打开命令提示符并执行pip install psycopg2-binary命令,如下所示 -

C:\WINDOWS\system32>pip install psycopg2-binary
Collecting psycopg2-binary
Using cached https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.3

确认

要验证安装,请创建一个示例 python 脚本,其中包含以下行。

import mysql.connector

如果安装成功,当您执行它时,您不应该收到任何错误 -

D:\Python_PostgreSQL>import psycopg2
D:\Python_PostgreSQL>

Python PostgreSQL - 数据库连接

PostgreSQL 提供了自己的 shell 来执行查询。要与 PostgreSQL 数据库建立连接,请确保您已在系统中正确安装它。打开 PostgreSQL shell 提示符并传递服务器、数据库、用户名和密码等详细信息。如果您提供的所有详细信息均正确,则会与 PostgreSQL 数据库建立连接。

在传递详细信息时,您可以使用 shell 建议的默认服务器、数据库、端口和用户名。

PostgreSQL shell 提示符

使用python建立连接

psycopg2的连接类表示/处理连接的实例。您可以使用connect()函数创建新连接。它接受基本连接参数,例如数据库名、用户、密码、主机、端口并返回连接对象。使用该函数,您可以与PostgreSQL建立连接。

例子

以下 Python 代码显示如何连接到现有数据库。如果数据库不存在,则会创建数据库,最后返回一个数据库对象。PostgreSQL 默认数据库的名称是postrgre。因此,我们将其作为数据库名称提供。

import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

输出

Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

Python PostgreSQL - 创建数据库

您可以使用 CREATE DATABASE 语句在 PostgreSQL 中创建数据库。您可以在 PostgreSQL shell 提示符下执行此语句,方法是在命令后指定要创建的数据库的名称。

句法

以下是 CREATE DATABASE 语句的语法。

CREATE DATABASE dbname;

例子

以下语句在 PostgreSQL 中创建一个名为 testdb 的数据库。

postgres=# CREATE DATABASE testdb;
CREATE DATABASE

您可以使用 \l 命令列出 PostgreSQL 中的数据库。如果验证数据库列表,您可以找到新创建的数据库,如下所示 -

postgres=# \l
                                           List of databases
Name       | Owner    | Encoding | Collate