这个问题已经有了答案:
Check if table exists [duplicate]
6个答案
我正在做一个程序,我可以从excel文件中读取数据并将它们存储在表中。每个表都有文件名和文件中的数据。
在程序结束时,我想检查用户是否给出了文件的正确路径,然后检查该表是否已经存在于数据库中。我该怎么做?我的意思是在从用户那里读取路径之后,我只想使用我在代码中指定为“tablename”的文件名来检查数据库中是否已经存在该文件。
下面是获取连接、给出路径和测试路径的程序。
用户应该给出的正确路径如下:c:\ users\myuser\docs\myfile.xls
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/kainourgia", "root", "root");
DatabaseMetaData meta = (DatabaseMetaData) con.getMetaData();
ResultSet res = meta.getCatalogs();
System.out.println("List of the databases: ");
while (res.next()) {
System.out.println(" " + res.getString(1));
}
String strfullPath = "";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Please enter the fullpath of the file:");
strfullPath = scanner.nextLine();
File f = new File(strfullPath);
if (f.canRead())
break;
System.out.println("Error:File does not exist");
}
String file = strfullPath.substring(strfullPath.lastIndexOf('/') + 1);
System.out.println(file.substring(0, file.indexOf('.')));
System.out.println("The path of the file is:");
String Path = strfullPath.substring(strfullPath.indexOf('\\') - 2,
(strfullPath.lastIndexOf('\\') - 2));
System.out.println(Path);
@SuppressWarnings("unused")
String filename = strfullPath
.substring(strfullPath.lastIndexOf('\\') + 1);
System.out.println("The filename is");
System.out.println(filename);
String[] parts = filename.split("\\.");
String tablename = parts[0];
DatabaseMetaData md2 = (DatabaseMetaData) con.getMetaData();
ResultSet rs = md2.getTables(null, null, "tablename", null);
System.out.println("The name of the table would be:");
System.out.println(tablename);
最佳答案
检查databasemetadata api,您应该能够获得所需的信息。以下是了解更多信息的链接:
http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html