sql语句是特别复杂的,java 怎么获取一条sql语句中所有的table,求解答
你这意思没看懂,table应该是sql语句去获取的,然后java通过执行sql语句得到,
获取所有table的sql就是:select table_name from information_schema.tables where table_schema='数据库名
' and table_type='base table';
select table_name from information_schema.tables where table_schema='数据库名
' and table_type='base table'
我试了一下 好像不行哦
可以试着将java类A里面的属性(int id,string name)与sql语句里面的table(int id,varchar(20) name)一一对应起来,这样应该就可以获取所有的table了
类似于这个的正则表达式,可以作为参考正则表达式获取sql语句中的表名
分析一下你的sql中表名所处的位置,例如,from后面,jion后面,找出规则,字符串截取。这是我的思路
public static void main(String[] args) {
String sql="select table_name from information_schema.tables where table_schema='数据库名' and table_type='base table' from information_schema.tables where from information_schema.tables where ";
StringBuffer sb = new StringBuffer();
List<Object> list = new ArrayList<>();
sb.append(sql);
Integer from = 0;
Integer last = 0;
while(last!=-1){
from = sb.indexOf("from");
last = sb.indexOf("where");
System.out.println(sb.substring(from+5,last));//截取表
list.add(sb.substring(from+5,last));//将表名放入list集合
System.out.println(sb.substring(last+5, sb.length()-1));
String aa=sb.substring(last+5, sb.length());//将sql截取,删除时java原则包括前不包括后
sb.setLength(0); //清空stringbuffer
sb.append(aa);//将截取剩下的sql放入stringbuffer
from = sb.indexOf("from");
last = sb.indexOf("where");//获取截取后的where的下标
}
}
获取所有from后的第一个字符串
想到的 就是用正则去取 就是不知道sql的结构
你可以用sql查到数据库所有的表然后用表面到sql
字符串里面indexOf找到表名,但是如果数据量大的话可能会慢
楼上的说的都一套一套的。。然而我还在呆呆中。。。不明白楼主说啥
package study;
import java.sql.*;
/**
* jdbc访问所有表
*/
public class FindAllTableJDBC {
//定义MySQL的数据库驱动程序
public static final String DB_DRIVER = "com.mysql.jdbc.Driver";
//定义MySQL数据库的连接地址
public static final String DB_URL = "jdbc:mysql://localhost:3306/db_learn";
//MySQL数据库的连接用户名和连接密码
public static final String DB_USER = "root";
public static final String DB_PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet ret = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
String sql = "select table_name from information_schema.tables where table_schema='db_learn' and table_type='base table';";
try {
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
pst = conn.prepareStatement(sql);//准备执行语句
ret = pst.executeQuery();
while (ret.next()) {
String tableName = ret.getString(1);
System.out.println("tableName="+tableName);
}
} catch (SQLException e1) {
e1.printStackTrace();
}finally {
if(ret!=null)
{
try {
ret.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
建议你看一下@TheTimeIsPassing 他回答的。已经很清楚了