Introduction to practical examples of ADO.NET
In order to give full play to the advantages of ADO.NET, it is not only necessary to have a comprehensive and in-depth understanding of the ADO.NET programming model, but it is also very important to summarize experience and skills in a timely manner. ADO has many years of practical experience, and ADO.NET provides richer and more powerful tools based on this. However, the design goal of ADO.NET is not to provide a plug-and-play tool after all, and it will not integrate all The programming work is simplified to the extent that it can be completed with just mouse clicks.
ADO.NET contains a large number of objects representing various logical entities in the data access model, among which the two objects of connection and transaction are the most important. The function of a connection is to establish a communication channel with the back-end database. Creating a connection object must be based on a specific .NET data provider. Transaction objects can be created on an existing connection object or by explicitly executing a BEGIN TRAN SQL statement. Although the theory is simple, in fact, there are many uncertain factors surrounding connections and transactions, and they have a crucial impact on the overall stability and efficiency of the application.
How to save the connection string and protect sensitive information (such as passwords) that may be contained in the connection string? How to design a complete data access policy that takes into account security (i.e. authentication, authorization) without having too much impact on performance and scalability? If transactions are needed, how to implement and control transactions efficiently? Use automatic transactions or manual transactions? When using ADO.NET, these issues must be carefully considered.
1. Connection string, connection pool
Database connection is an important, limited, and expensive resource, so making good use of connection objects is the most basic requirement for any application. The key points of using database connections can be summarized as follows:
Pay attention to safety when saving connection strings.
The connection should be opened late and the connection should be closed early.
The connection string is the key to access the database. In addition to describing the data to be accessed, the connection string also contains proof of identity of why the user can access that data. User authentication is the most important factor in determining data access rights when performing database operations.
1.1 Saving connection strings
Currently, hard-coded connection strings have the best performance because they are compiled directly into the application code. However, hard-coded strings affect the flexibility of the program, and the application must be recompiled once the connection string changes.
Saving the connection string externally increases flexibility, at the expense of additional overhead for accessing the external string. But in the vast majority of cases, the resulting performance overhead is negligible, and what you really need to worry about is security. For example, an attacker could modify or steal the connection string. Common ways to save the connection string to the external environment are: Configuration file, UDL file, Windows registry.
.NET framework configuration files are deployed in the form of plain text files and are easy to access. If the connection string contains a password, the text format will be the biggest drawback, because the password will be saved in clear text. You can consider introducing a dedicated encryption/decryption engine, but this part of the work needs to be done by the developers themselves.
UDL files are text files used by OLE DB providers, that is, SQL Server hosting providers do not support UDL files. UDL files also have the same security issues as the previous configuration files, and overall there are not many advantages.
Finally, the Windows registry can be used as a naturally secure storage place. The registry is a system knowledge base that stores key information. If combined with encryption technology, higher security can be achieved. The main disadvantages of using a registry are the hassle of deployment, the requirement to create registry keys (and possibly perform encryption) and to read data from the registry. Although the .NET Framework provides a set of encapsulated classes that call the underlying Win32 API, none of these classes provide encryption functions. The aspnet_setreg.exe tool can be used to create a registration key under HKEY_LOCAL_MACHINE to save the user name and password, for example: aspnet_setreg.exe -k "Software\MyData" -u:userID -p:password. This command will encrypt the specified user ID and password.
1.2 Connection Pool Principle
The connection pool allows us to reuse existing connection objects through a buffer pool, avoiding the need to create a new object every time a connection object is used. After using the connection pool, only a small number of connection objects can meet the needs of a large number of clients.
Each connection pool is associated with an independent connection string and its transaction context. Each time a new connection is opened, the data provider attempts to match the specified connection string with the connection pool's string. If the match fails, the data provider creates a new connection and adds it to the connection pool. After the connection pool is created, it will not be dismantled unless the process ends. Some people think that this processing method will affect performance. In fact, it does not cost much to maintain an inactive or empty connection pool.
After the connection pool is created, the system will create some connection objects and add them to the connection pool until the rated minimum number of connection objects is reached. In the future, the system will create and add connection objects as needed until the maximum number of connection objects is reached. If there is no free connection object available when the program requests a connection object, and the number of objects in the connection pool has reached the upper limit, the request is placed in the queue, and once a connection is released back to the buffer pool, it is immediately taken out for use.
Avoid constructing connection strings programmatically. If the connection string is constructed by merging multiple input data, it is easy for injection attacks to take advantage of it. If user-entered data must be used, strict validation must be performed.
1.3 Closing the connection
When closing a connection, the connection object is returned to the connection pool for reuse, but the actual database connection is not dismantled at this time. If connection pooling is disabled, the actual database connection is also closed. One point that must be emphasized here is that the connection object should be explicitly closed and returned to the connection pool after use. Do not rely on the garbage collector to release the connection. In fact, when the reference of the connection object goes out of the valid range, the connection is not necessarily closed - the function of the garbage collector is to tear down the .NET encapsulated object representing the physical connection, but this does not mean that the underlying The connection is also closed.
Calling the Close or Dispose method can release the connection back to the connection pool. The connection object will be deleted from the connection pool only when the lifetime ends or a serious error occurs.
1.4 Connection Pooling and Security
If all data access operations of an application use the same connection string, the advantages of the connection pool will be maximized. However, this is an idealized situation and may conflict with other requirements of the application. For example, it would be difficult to enforce security controls at the database level if only a single connection string was used.
On the other hand, if each user is allowed to use his own connection string (that is, a separate database account is set for each user), there will inevitably be a large number of small connection pools, and many connections will not be reused at all. . Conventionally, the best solution to this type of problem is to find an appropriate compromise between the two extremes. We can set up a representative set of public accounts and modify the stored procedure to accept a parameter representing the user ID. The stored procedure performs different operations based on the incoming user ID.
2. Transaction Mode
Distributed enterprise applications are inseparable from transactions. There are two main ways to add transaction management functions to data access code: manual and automatic.
In the manual method, the programmer is responsible for writing all code that configures and uses the transaction mechanism. Automatic (or COM+) transactions add declarative attributes to .NET classes to specify the transactional characteristics of runtime objects. The automated approach facilitates configuring multiple components to run within the same transaction. Both transaction methods support local or distributed transactions, but the automatic transaction method greatly simplifies distributed transaction processing.
It must be noted that transactions are a very expensive operation, so you must think twice before deciding to use transactions. If you really need to use transactions, you should try to reduce the granularity of the transactions and reduce the locking time and locking scope of the database. For example, for SQL Server, a single SQL statement does not need to explicitly declare a transaction, SQL Server will automatically run each statement as an independent transaction. Manual local transactions are always much faster than other transactions because it does not need to involve DTC (Distributed Transaction Coordinator).
Manual transactions and automatic transactions should be regarded as two different and mutually exclusive technologies. If you want to perform transactional operations on a single database, give priority to manual transactions. When a single transaction spans multiple remote databases, or a single transaction involves multiple resource managers (for example, one database and one MSMQ resource manager), automatic transactions are given priority. Regardless, mixing the two transaction modes should be avoided as much as possible. If performance is not particularly important, consider using automatic transactions even for only one database operation, making the code cleaner (but slightly slower).
In short, to improve the quality of database access code, you must have an in-depth understanding of the ADO.NET object model and flexibly use various techniques according to the actual situation. ADO.NET is a public API. Various applications, whether it is Windows Forms applications, ASP pages or Web services, can access the database through ADO.NET; however, ADO.NET does not accept input and spit out results at the same time. A black box, but a toolbox made up of many tools.
The above is the detailed content of Introduction to practical examples of ADO.NET. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

PyCharm Beginner's Guide: Practical Tips for Deleting Projects PyCharm is a powerful Python integrated development environment (IDE). When developing projects, sometimes you need to delete projects or files in the projects. This article will introduce practical techniques for deleting projects in PyCharm, and provide specific code examples to help novices better understand and apply. 1. Delete the project Deleting the project means deleting the entire project folder, which is very useful when we need to clean or rebuild the project. Delete in PyCharm

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Introduction to Python functions: Introduction and examples of exec function Introduction: In Python, exec is a built-in function that is used to execute Python code stored in a string or file. The exec function provides a way to dynamically execute code, allowing the program to generate, modify, and execute code as needed during runtime. This article will introduce how to use the exec function and give some practical code examples. How to use the exec function: The basic syntax of the exec function is as follows: exec

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

In today's fast life, in order to improve work efficiency, shortcut keys are an essential work requirement. A shortcut key is a key or key combination that provides an alternative way to perform an action normally performed using a mouse. So what are the edge shortcut keys? What are the functions of edge shortcut keys? The editor below has compiled an introduction to edge shortcut keys. Friends who are interested should come and take a look! Ctrl+D: Add the current page to favorites or reading list Ctrl+E: Perform a search query in the address bar Ctrl+F: Find on the page Ctrl+H: Open the history panel Ctrl+G: Open the reading list panel Ctrl +I: Open the favorites list panel (the test does not seem to work) Ctrl+J: Open
