Table of Contents
2.StringBuilder forms DQL" >2.StringBuilder forms DQL
condition is generated. Determine whether there is a query condition in front. " > If the query condition is the first query condition, there is no need to add "and", otherwise the problem becomes complicated, and it is required every time the query condition is generated. Determine whether there is a query condition in front.
When assigning a value to a placeholder, you not only need to pass the data to the placeholder, but also need to select a data type that is consistent with the field. The List collection only stores data and is no longer " > When assigning a value to a placeholder, you not only need to pass the data to the placeholder, but also need to select a data type that is consistent with the field. The List collection only stores data and is no longer
3.服务器端(Servlet)" >3.服务器端(Servlet)
Home Database Mysql Tutorial How does JDBC implement dynamic query?

How does JDBC implement dynamic query?

Jul 21, 2017 pm 02:12 PM
jdbc accomplish Inquire

In network development, comprehensive queries with multiple conditions are very common. To deal with this business need, we usually use the following methods to achieve it:
1. Directly Splice the parameter values ​​into the SQL statement and then query.
The security of this method should be said to be relatively poor, and it can be accidentally injected by SQL. Although you can filter special characters in parameter values ​​first, it doesn't always feel very elegant.
2. Use placeholder '? ' to splice SQL, and then fill in the PreparedStatement through conditional judgment.
Anyone who has used TX in this way knows the complexity of this method. First, you have to make a judgment once when you are spelling SQL, and then you have to make a judgment again when filling in PST, which is troublesome.
3. Procedure Storage
I have always been unhappy with stored procedures. I once had a project migrated from MySQL to MSSQL, and later to ORACLE. In the end, different versions of the product ran on different databases, and I almost had to do it at that time. It’s my life.
In fact, all I have to say is that I want a relatively elegant and simple query method. I was inspired by the SQLHelper provided in .NET in the previous paragraph, and then I wrote such a similar component (in fact, I Googled half of it No foundation that meets the requirements has been found for hours

1. What is dynamic query?

## Randomly select from multiple query conditions. Several are combined into one DQL statement for query. This process is called dynamic query

2. Difficulties of dynamic query

## Available options. There are many query conditions and many combinations, making it difficult to list them all. 3. The composition of the final query statement

Once the user submits the query conditions. Enter data into the query condition, and the query condition becomes part of the final condition. 2. Basic principles

1.SQL basic framework

Regardless of the query conditions, the query fields and the database are fixed. These fixed contents constitute the basic framework of the SQL statement, such as

select column... from table。
Copy after login

2.StringBuilder forms DQL

Get form input. If the request parameter is not empty, generate query conditions based on the request parameter, such as "name=?", "age> ;?", append the query conditions to the

basic framework. Use StringBuilder to append the query conditions. At this time, a question arises. How to judge whether "and" needs to be added to the generated query conditions?

If the query condition is the first query condition, there is no need to add "and", otherwise the problem becomes complicated, and it is required every time the query condition is generated. Determine whether there is a query condition in front.

We can consider adding a query condition in the basic SQL framework. The existence of the query condition does not affect the query results and only acts as a placeholder to avoid dynamic Determine whether "and" needs to be added when adding query conditions. According to these requirements, this query condition must always be true. Here we take "1=1", and the basic SQL
framework becomes

select column...from table where 1=1
Copy after login

Add "and" in front of each dynamic query condition 3. The List collection is a placeholder. Character assignment

With the DQL statement, you need to consider how to assign values ​​to the placeholders. You can collect the parameters corresponding to the placeholders and store them# while generating the query conditions.

##In an ordered collection, the List collection is selected here, so that the placeholders form a sequential correspondence with the elements in the List collection. The nth placeholder corresponds to the nth placeholder. elements, you can assign values ​​to the placeholders by traversing the collection.

When assigning a value to a placeholder, you not only need to pass the data to the placeholder, but also need to select a data type that is consistent with the field. The List collection only stores data and is no longer

To meet the requirements, you still need to add field information to distinguish different fields and select different data types. The elements in the collection here are in the form of

"column+data". 三Demo
1. Database

2.Page

<!DOCTYPE html><html><head><meta charset="UTF-8"><style>span {display: inline-block;width: 75px;margin-bottom: 15px;}</style><title>动态查询</title></head><body><form action="http://localhost:8080/JavaSETest/dynamicQueryServlet"><div><span>姓名:</span><input type="text" name="name"></div><div><span>性别:</span><input type="text" name="sex"></div><div><span>年龄:</span><input type="text" name="age"></div><div><span>部门编号:</span><input type="text" name="depNo"></div><div><input type="submit"value="查询"> <input type="reset"value="重置"></div></form></body></html>
Copy after login

3.服务器端(Servlet)

"/dynamicQueryServlet"  DynamicQueryServlet     serialVersionUID = 1L "text/html;charset=UTF-8"String name = request.getParameter("name"= request.getParameter("sex"= request.getParameter("age"= request.getParameter("depNo"String baseSQL = "select name,sex,age,depNo from tb_employee where 1=1"=  StringBuilder();List<String> params =  ArrayList<String>" and name=? ""name," + name);" and sex=? ""sex," +" and age=? ""age," +" and depNo=?""depNo," += = = = == ( i = 0; i < params.size(); i++== str.split(","); (arr[0].equals("age" a = Integer.parseInt(arr[1+ 1+ 1, arr[1== res.getString("name"= res.getString("sex" targetAge = res.getInt("age"= res.getString("depNo"= "name=" + targetName + "--" + "sex=" + targetSex + "--" + "age=" + targetAge + "--"
                        + "depNo=" ++ "<br>" (ClassNotFoundException | (res !=  (ps !=  (conn != = length = (length == 0"查询为空"+ "<br>" +   (str ==  | str.equals(""    Connection getConnection() "com.mysql.jdbc.Driver" DriverManager.getConnection("jdbc:mysql://localhost:3366/test01", "root", "123"
Copy after login

The above is the detailed content of How does JDBC implement dynamic query?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

12306 How to check historical ticket purchase records How to check historical ticket purchase records 12306 How to check historical ticket purchase records How to check historical ticket purchase records Mar 28, 2024 pm 03:11 PM

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

How to check your academic qualifications on Xuexin.com How to check your academic qualifications on Xuexin.com Mar 28, 2024 pm 04:31 PM

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Comparison of similarities and differences between MySQL and PL/SQL Comparison of similarities and differences between MySQL and PL/SQL Mar 16, 2024 am 11:15 AM

MySQL and PL/SQL are two different database management systems, representing the characteristics of relational databases and procedural languages ​​respectively. This article will compare the similarities and differences between MySQL and PL/SQL, with specific code examples to illustrate. MySQL is a popular relational database management system that uses Structured Query Language (SQL) to manage and operate databases. PL/SQL is a procedural language unique to Oracle database and is used to write database objects such as stored procedures, triggers and functions. same

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

See all articles