MySQL 动态条件查询是指根据不同的条件动态生成 SQL 查询语句。这种查询方式可以根据用户的输入或其他变量的值来决定查询的条件,从而实现灵活的数据检索。
PreparedStatement
)来防止 SQL 注入,并提高查询效率。以下是一个基于字符串拼接的动态条件查询示例:
import java.sql.*;
public class DynamicQueryExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String baseQuery = "SELECT * FROM users WHERE 1=1";
StringBuilder queryBuilder = new StringBuilder(baseQuery);
List<Object> params = new ArrayList<>();
String name = "John";
if (name != null && !name.isEmpty()) {
queryBuilder.append(" AND name = ?");
params.add(name);
}
int age = 25;
if (age > 0) {
queryBuilder.append(" AND age = ?");
params.add(age);
}
String sql = queryBuilder.toString();
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i + 1, params.get(i));
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Age: " + rs.getInt("age"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
PreparedStatement
)可以有效防止 SQL 注入攻击。通过以上方法,可以有效地实现 MySQL 动态条件查询,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云