我正在创建一个程序,我将从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);
答案 0 :(得分:2)
检查DatabaseMetadata api,您应该能够获得所需的信息。以下是了解更多相关信息的链接:
http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html