我要查询的是字段值,不是列名
时间: 2024-03-27 18:38:35 浏览: 17
如果要查询一个字符串值是否在一个数据库中任意表中存在,需要根据具体的数据库类型和表结构编写SQL语句。以下是一个示例代码,用于在MySQL数据库中查询一个字符串值是否在任意表中的任意列中出现过:
```java
import java.sql.*;
public class CheckStringInDB {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 建立数据库连接
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
con = DriverManager.getConnection(url, user, password);
// 2. 编写查询语句
String query = "SELECT * FROM information_schema.columns WHERE table_schema = 'mydatabase' AND table_name NOT IN ('table1', 'table2') AND column_type LIKE '%char%' AND CONCAT('SELECT * FROM ', table_name, ' WHERE ', column_name, ' = ''mystring''')";
// 3. 执行查询语句
stmt = con.createStatement();
rs = stmt.executeQuery(query);
// 4. 遍历查询结果
if (rs.next()) {
System.out.println("String exists in database.");
} else {
System.out.println("String does not exist in database.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5. 关闭连接和查询结果
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码会查询除了 `table1` 和 `table2` 之外的所有表中的所有字符类型列,然后组合成一个新的SQL语句进行查询,最后判断查询结果是否存在。需要根据具体的需求和表结构进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)