sql crud

This article covers how to connect a Python application to Microsoft SQL Server using a 3rd party Python SQL library. The library that we are going to use is called “pyodbc”, which is freely available. We will use “pyodbc” to perform CRUD (Create Read Update and Delete) operations on a Microsoft SQL Server database.

本文介绍如何连接使用第三方的Python SQL库Python应用程序到Microsoft SQL Server。 我们将要使用的库称为“ pyodbc”,可免费使用。 我们将使用“ pyodbc”在Microsoft SQL Server数据库上执行CRUD(创建读取更新和删除)操作。

创建一个虚拟数据库 (Creating a dummy database)

The first step is to create a dummy database. Execute at the following script:

第一步是创建一个虚拟数据库。 执行以下脚本:

CREATE DATABASE LibraryDB

The script above creates a database named “LibraryDB” in MS SQL Server.

上面的脚本在MS SQL Server中创建一个名为“ LibraryDB”的数据库。

We will create one table i.e. Books in the LibraryDB as shown in the following script:

我们将在LibraryDB中创建一个表,即Books,如以下脚本所示:

USE LibraryDB
CREATE TABLE Books
(
Id INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR (50) NOT NULL,
Price INT
)

The above script creates a table named “Books” in the “LibraryDB” database that we created earlier. The “Books” table contains three columns: Id, Name, and Price. The Id column is the primary key column and it cannot be NULL.

上面的脚本在我们之前创建的“ LibraryDB”数据库中创建了一个名为“ Books”的表。 “书籍”表包含三列:Id,名称和价格。 Id列是主键列,不能为NULL。

使用PYODBC Python SQL库 (Working with PYODBC Python SQL Library)

To work with the pyodbc library, you first need to install it. In Python environments, you can use pip installers to install Python libraries. Before you can run Python SQL queries on MS SQL Server, from within a Python application, execute the following command at the terminal to install pyodbc library:

要使用pyodbc库,首先需要安装它。 在Python环境中,您可以使用pip安装程序来安装Python库。 在可以从Python应用程序中在MS SQL Server上运行Python SQL查询之前,请在终端上执行以下命令以安装pyodbc库:

$ pip install pyodbc

与数据库连接 (Connecting with the Database)

To execute Python SQL queries from a Python application, first, you need to make a connection to the MS SQL Server database. Execute the following script in your Python application:

要从Python应用程序执行Python SQL查询,首先,您需要建立与MS SQL Server数据库的连接。 在您的Python应用程序中执行以下脚本:

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};''Server=DESKTOP-IIBLKH1\SQLEXPRESS;''Database=LibraryDB;''Trusted_Connection=yes;')

In the above script, we first import the pyodbc module and then call the “connect()” method to connect to an MS SQL Server database.

在上面的脚本中,我们首先导入pyodbc模块,然后调用“ connect()”方法连接到MS SQL Server数据库。

For the Server parameter, you need to specify the name of your own MS SQL database server. Similarly, you will need to update the database name if you want to connect to a different database. The connect() method returns a connection object.

对于Server参数,您需要指定自己的MS SQL数据库服务器的名称。 同样,如果要连接到其他数据库,则需要更新数据库名称。 connect()方法返回一个连接对象。

To execute queries, the “cursor()” object of the connection object is used. The following script stores the cursor object in the “cursor” variable:

要执行查询,请使用连接对象的“ cursor()”对象。 以下脚本将光标对象存储在“ cursor”变量中:

cursor = conn.cursor()

Now is the time to perform CRUD operation on our database by executing Python SQL queries from within a Python application.

现在是时候通过从Python应用程序中执行Python SQL查询来对数据库执行CRUD操作了。

创建记录 (Creating records)

There are two ways to insert records in a database via pyodbc library. You can insert a single record with the “execute()” method of the cursor object or you can insert multiple records via “executemany()” method.

通过pyodbc库有两种在数据库中插入记录的方法。 您可以使用光标对象的“ execute()”方法插入一条记录,也可以通过“ executemany()”方法插入多个记录。

插入一条记录 (Inserting a single record)

Let’s first see how to insert a single record:

首先让我们看看如何插入一条记录:

name = "Book - A"
price = 125insert_records = '''INSERT INTO Books(Name, Price) VALUES(?,?) '''
cursor.execute(insert_records, name, price)
conn.commit()

The INSERT query in pyodbc is similar to any other SQL query. However, for the database values in the VALUES clause, you can pass question marks.

pyodbc中的INSERT查询与任何其他SQL查询相似。 但是,对于VALUES子句中的数据库值,可以传递问号。

To insert records, the query string is passed to the “execute()” method as a parameter along with the values to be inserted. The above script will insert a single record in the Books table of the LibraryDB database. It is important to mention that you have to call the “commit()” method of the connection object once you insert, update, or delete records from a database.

要插入记录,查询字符串将作为参数与要插入的值一起传递给“ execute()”方法。 上面的脚本将在LibraryDB数据库的Books表中插入一条记录。 重要的是要提到,一旦从数据库中插入,更新或删除记录,就必须调用连接对象的“ commit()”方法。

插入多条记录 (Inserting multiple records)

The following script inserts multiple records in the Books table:

下面的脚本在Books表中插入多个记录:

record_1= ["Book - B", 300]
record_2= ["Book - C", 200]record_list = []
record_list.append(record_1)
record_list.append(record_2)insert_records = '''INSERT INTO Books(Name, Price) VALUES(?,?) '''
cursor.executemany(insert_records, record_list)
conn.commit()

To insert multiple records, the “executemany()” method is used. The first parameter to the method is the INSERT query string, the second parameter is the list of records that you want to insert. In the script above, we create two lists i.e. record_1 and record_2. These two lists are then appended in another list named record_list, which is in turn passed as the second parameter to the “executemany()” method.

要插入多个记录,请使用“ executemany()”方法。 该方法的第一个参数是INSERT查询字符串,第二个参数是要插入的记录列表。 在上面的脚本中,我们创建两个列表,即record_1和record_2。 然后,将这两个列表附加到另一个名为record_list的列表中,该列表又作为第二个参数传递给“ executemany()”方法。

We have inserted a total of three records in the libraryDB dataset via Python SQL INSERT query. Let’s now see how we can select records.

通过Python SQL INSERT查询,我们在libraryDB数据集中总共插入了三个记录。 现在让我们看看如何选择记录。

选择记录 (Selecting records)

To select records, the SELECT query is passed to the “execute()” method. The following script retrieves all the records from the Books table:

要选择记录,将SELECT查询传递给“ execute()”方法。 以下脚本从“ Books”表中检索所有记录:

select_record = '''SELECT * FROM Books'''
cursor.execute(select_record)for row in cursor:print(row)

The SELECT query returns an iterator object where each item corresponds to a database record. The iterator object can be iterated and the records can be printed via a For loop. Once you execute the above script, you should see the following records in the output:

SELECT查询返回一个迭代器对象,其中每个项目对应于一个数据库记录。 可以迭代迭代器对象,并可以通过For循环打印记录。 一旦执行了上面的脚本,您应该在输出中看到以下记录:

You can see the three records that we inserted in the Books table, in the last section.

您可以在最后一部分中看到我们在Books表中插入的三个记录。

更新记录 (Updating records)

To update records, again the “execute()” method of the cursor object can be used. After the execute() method, you need to call the “commit()” method of the connection object. The following query updates the price of the book whose Id is 1:

要更新记录,可以再次使用游标对象的“ execute()”方法。 在执行execute()方法之后,您需要调用连接对象的“ commit()”方法。 以下查询更新ID为1的图书的价格:

update_query = '''UPDATE Books SET Price = 400 WHERE Id= 1'''
cursor.execute(update_query)
conn.commit()

Now if you again select all the records from the Books table, you will see the following output:

现在,如果再次从Books表中选择所有记录,将看到以下输出:

You can see that the price of the book with Id 1 has been updated to 400.

您可以看到带有ID 1的书的价格已更新为400。

删除记录 (Deleting records)

To delete records from an MS SQL Server database, using a Python SQL DELETE query from a Python application, you can use the following script:

要从MS SQL Server数据库中删除记录,请使用Python应用程序中的Python SQL DELETE查询,可以使用以下脚本:

delete_query = '''DELETE FROM Books WHERE Id= 1'''
cursor.execute(delete_query )
conn.commit()

The above script deletes all the records from the Books table, where Id is 1.

上面的脚本从ID为1的Books表中删除所有记录。

To delete records, again you can use the “execute()” method of the cursor object. The query for deleting records is passed as a parameter to the “execute()” method. You need to call the “commit()” method, once the records are deleted.

要删除记录,可以再次使用游标对象的“ execute()”方法。 删除记录的查询作为参数传递给“ execute()”方法。 删除记录后,您需要调用“ commit()”方法。

Now, if you select all the records from the Books table, you should see the following output:

现在,如果您从“书籍”表中选择所有记录,则应该看到以下输出:

You can see that the record with Id 1 has been deleted.

您可以看到具有ID 1的记录已被删除。

结论 (Conclusion)

Python SQL queries are used to interact with different database servers from within a Python application. This article explains how to execute Python SQL queries using pyodbc library, in order to interact with Microsoft SQL Server Database.

Python SQL查询用于在Python应用程序中与不同的数据库服务器进行交互。 本文介绍了如何使用pyodbc库执行Python SQL查询,以便与Microsoft SQL Server数据库进行交互。

翻译自: https://www.sqlshack.com/performing-crud-operations-with-a-python-sql-library-for-sql-server/

sql crud

sql crud_使用适用于SQL Server的Python SQL库执行CRUD操作相关推荐

  1. 使用SQL数据库在Python中执行CRUD操作

    目录 介绍 背景 在Visual Studio中创建一个Python项目 在SQL中创建数据库和表 为数据库创建配置文件 安装Python包 "Pypyodbc" 创建连接文件 创 ...

  2. vue.js crud_如何使用VS Code和ADO.NET使用ASP.NET Core执行CRUD操作

    vue.js crud 介绍 (Introduction) In this article we are going to create a web application using ASP.NET ...

  3. python安装库 换源操作

    1 常用源 # 腾讯 http://mirrors.tencentyun.com/pypi/simple # 阿里 https://mirrors.aliyun.com/pypi/simple # 豆 ...

  4. python itchat库安装_操作微信-itchat库的安装

    基于pyCharm开发环境,在CMD控制台输入:pip install itchat      等待安装...... Microsoft Windows [版本 6.1.7601] 版权所有 (c) ...

  5. Python PIL库处理图片常用操作,图像识别数据增强的方法

    在博客AlexNet原理及tensorflow实现训练神经网络的时候,做了数据增强,对图片的处理采用的是PIL(Python Image Library), PIL是Python常用的图像处理库. 下 ...

  6. python算法库执行效率_Python智能优化算法库小汇总

    最近查了一圈python的智能优化算法库,发现在python里面这样的库相对一些传统的语言还真是不太多(比如Matlab).总的看起来似乎起步都还比较晚(个人认为有可能是因为智能算法本身相对复杂并且过 ...

  7. Python高级:数据库CRUD操作

    文章目录 知识目标 知识点 ①Python数据库接口 ②连接MySQL数据库 ③数据库的操作 知识目标 1.了解PyMySQL 2.掌握PyMySQL连接数据库 3.掌握PyMySQL操作数据库的步骤 ...

  8. php 命令执行crud_如何使用原始JavaScript执行CRUD操作

    php 命令执行crud by Zafar Saleem 通过Zafar Saleem 如何使用原始JavaScript执行CRUD操作 (How to perform CRUD operations ...

  9. python怎么执行csv文件_无法读取/打开/或对CSV文件python 3.4windows执行任何操作

    我无法打开程序生成的任何CSV文件(我没有程序的完整详细信息),它的文件名为266925.130314-88850999.word 文件是csv,它在excel 2013中打开,所有编辑器都很好,我尝 ...

最新文章

  1. pymysql.err.InterfaceError: (0, '')
  2. 003_如何创建CSS
  3. ug11许可证文件路径安装在哪_Matlab2012a安装教程
  4. Spring boot整合dubbo
  5. SpringBoot中Profile配置和加载配置文件
  6. C#——Lambda表达式与泛型委托DEMO
  7. LintCode 802. 数独(回溯)/ LeetCode 37. 解数独
  8. 在 IntelliJ IDEA 中部署应用到服务器(Eclipse)
  9. 简单的签到代码_PHP实现一个小小的签到功能,到底用MySQL还是Redis?
  10. 信息学奥赛一本通C++语言——1097:求阶乘的和
  11. WPF: 本地化(Localization) 实现
  12. mysql msdtc 不支持_MSDTC”该伙伴事务管理器已经禁止了它对远程网络事务的支持”的错误(转) | 学步园...
  13. Opencv系列1_opencv对单张DCM文件的读取并显示
  14. word自带参考文献标注功能
  15. vue 动态显示图片报错 404
  16. Linux下如何解压bz2文件
  17. 《我的菜谱》-西红柿炒鸡蛋
  18. 大数据产品价值主张_大数据背景下新零售商业模式探究
  19. 混合易失和非易失主存的日志结构文件系统NOVA[FAST'16]随笔二
  20. java gbk转机内码_Java实现的UTF-8,GBK,Unicode编码相互转换的代码

热门文章

  1. 【InnoDB】体系结构
  2. 正确停掉 expdp 或 impdp
  3. 结构体在固件库中的应用
  4. JQuery和JavaScript常用方法的一些区别
  5. Android的图片压缩并上传
  6. 说道说道 ios 图片尺寸的问题
  7. 【XAMPP启动mysql报错】Port 3306 in use by ““C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld“……
  8. JavaScript实现中国地图圆点标注(二十四)
  9. 商业医疗险住院报销需要什么材料?
  10. 你认识的有钱人,是怎么起家的?是做什么生意的?