以下 Java 代码循环遍历每个表中的每个 VARCHAR/NVARCHAR 列,并SELECT TOP 1
对该列执行 a 以查看它是否被命中:
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBCQuery {
public static void main(String args[]) {
String textToSearchFor = "Gord"; // test data
System.out.println(String.format("The value '%s' was found in the following locations:", textToSearchFor));
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String connectionString =
"jdbc:odbc:Driver={SQL Server};" +
"Server=.\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=myDb";
conn = DriverManager.getConnection(connectionString);
DatabaseMetaData md = conn.getMetaData();
ResultSet mdrs = md.getTables(null, null, "%", new String[] { "TABLE" });
List<String> tableList = new ArrayList<String>();
while (mdrs.next()) {
tableList.add(String.format("[%s].[%s].[%s]", mdrs.getString(1), mdrs.getString(2), mdrs.getString(3)));
// i.e., [catalogName].[schemaName].[tableName]
}
mdrs.close();
for (String tableName : tableList) {
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM " + tableName + " WHERE 0=1");
ResultSet rs0 = stmt.getResultSet();
ResultSetMetaData rsmd = rs0.getMetaData();
List<String> columnList = new ArrayList<String>();
for (int colIndex = 1; colIndex <= rsmd.getColumnCount(); colIndex++) {
switch (rsmd.getColumnType(colIndex)) {
case java.sql.Types.VARCHAR:
case java.sql.Types.NVARCHAR:
columnList.add("[" + rsmd.getColumnName(colIndex) + "]");
break;
}
}
rs0.close();
stmt.close();
for (String columnName : columnList) {
String psSql = String.format("SELECT TOP 1 * FROM %s WHERE %s = ?", tableName, columnName);
ps = conn.prepareStatement(psSql);
ps.setString(1, textToSearchFor);
ResultSet rs1 = ps.executeQuery();
if (rs1.next()) {
System.out.println(String.format("column %s in %s", columnName, tableName));
}
rs1.close();
ps.close();
}
}
} catch( Exception e ) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch( Exception e ) {
e.printStackTrace();
}
}
}
}
结果如下所示;
The value 'Gord' was found in the following locations:
column [textCol] in [myDb].[dbo].[linkedTable]
column [FirstName] in [myDb].[dbo].[myContacts]