1

我正在制作一个程序,我将从 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);
4

1 回答 1

2

检查 DatabaseMetadata api,您应该能够获得所需的信息。这是了解更多信息的链接:

http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html

于 2013-05-16T11:00:31.720 回答