0

我正在使用 Java 编写一个 Web 服务来与我在我的 localhost 机器上运行的 MySQL 服务器上设置的数据库进行通信。我的方法 ListColumns() 用于查找指定表中列的名称并将它们从 ResultSet 转换为数组,然后返回该数组;正在返回一个正确大小的数组,但它是完整的“空”值。

    import java.sql.*;

public class DBConnect {

private Connection con;
private Statement st;
private ResultSet rs;

public DBConnect(){
    try{
        Class.forName("com.mysql.jdbc.Driver");
        String database = "jdbc:mysql://localhost:3306/binapartslist";
        String userID = "root";
        String userPW = "root";     
        //jdbc:mysql://localhost:3306/`database name` --> This is the database
        //userID database user
        //userPW user password

        //Connecting to the database
        con = DriverManager.getConnection(database, userID, userPW);
        st = con.createStatement();
    }
    catch(Exception ex){
        System.out.println("Error: "+ex);
    }
}
public String getUser(){
    try{
        DatabaseMetaData dmd = con.getMetaData();
        String username = dmd.getUserName();
        //System.out.println("Current User: "+username);
        return username;
    }catch(Exception ex){
        System.out.println(ex);
        return null;
    }
}
public void getData(String table){
    int i=1;
    try{

        String query = "select * from "+table;
        rs = st.executeQuery(query);
        System.out.println("Records from Database");

        String[] columnNames = ListColumns(table);
        int count = columnNames.length;
        System.out.println(ListColumns(table));

        System.out.println("number of columns "+count);         
        for(i=0; i<count; i++){
            System.out.println(columnNames[i]);
        }

    }catch(Exception ex){
        System.out.println(ex);
    }

}
public int countTables (String database){
    try{
        DatabaseMetaData dmd = con.getMetaData();
        rs= dmd.getTables(null, database, "%", null);

        int count=0;
        while(rs.next()){
            count++;
        }
        return count;

    }catch(Exception ex){
        System.out.println(ex);         
        return 0;
    }

}   
public int countColumns (String table){
    try{
        DatabaseMetaData dmd = con.getMetaData();
        rs = dmd.getColumns(null, null, table, "%");

        int count=0;
        while(rs.next()){
            count++;
        }
        return count;

    }catch(Exception ex){
        System.out.println(ex);         
        return 0;
    }

}
public String[] ListColumns(String table){
    String[] columnsList = new String[countColumns(table)];
    try{            
        DatabaseMetaData dmd = con.getMetaData();
        rs = dmd.getColumns(null, null, table, "%");

        int i=0;
        while(rs.next()){
            columnsList[i]=rs.getString("COLUMN_NAME");
            i++;
        }
        System.out.println("columnsList[] has "+columnsList.length+" values");
        for(i=0;i<columnsList.length;i++){
            System.out.println("Column Name: "+columnsList[i]);
        }
        return columnsList;         
    }catch(Exception ex){
        System.out.println("i screwed up");
        System.out.println(ex);         
        return columnsList;
    }
}
public String[] ListTables(String database){
    try{
        DatabaseMetaData dmd = con.getMetaData();
        rs = dmd.getTables(null, database, "%", null);

        System.out.println(database);
        String[] tablesList = new String[countTables(database)];
        int i=0;
        while (rs.next()) {
            tablesList[i]=rs.getString("TABLE_NAME");
            System.out.println("table name: "+rs.getString(3));
            i++;
        }               
        return tablesList;
    }catch(Exception ex){
        System.out.println(ex);
        return null;
    }
}
public void createUser(String username, String password, String rank) throws SQLException{
    try{
        con.setAutoCommit(false);
        st.executeUpdate("INSERT INTO `users` VALUES ('"+username+"', '"+password+"', '"+rank+"');");
        con.commit();
        con.setAutoCommit(true);
    }catch (Exception ex ) {
        System.out.println(ex);
            if (con != null) {
                try {
                    System.err.print("Transaction is being rolled back");
                    con.rollback();
                }catch(Exception excep) {
                    if (con != null) {
                        con.rollback();
                        con.setAutoCommit(true);
                      }
                    System.out.println(excep);
                }
            }
    }
}
public void deleteUser(String username) throws SQLException{
    try{
        con.setAutoCommit(false);
        st.executeUpdate("DELETE FROM `users` WHERE username = '"+username+"'");
        con.commit();
        con.setAutoCommit(true);
    }catch (Exception ex ) {
        System.out.println(ex);
            if (con != null) {
                try {
                    System.err.print("Transaction is being rolled back");
                    con.rollback();
                }catch(Exception excep) {
                    if (con != null) {
                        con.rollback();
                        con.setAutoCommit(true);
                      }
                    System.out.println(excep);
                }
            }
    }
}

}

我正在使用以下代码调用这些方法所在的类:

    import java.sql.SQLException;

    public class Main
    {
        public static void main(String[] args) throws SQLException {
            DBConnect connect = new DBConnect();
            System.out.println(connect.getUser());
            System.out.println(connect.ListColumns("parts list"));
            connect.ListColumns("parts list");
        }


    }

我需要 columnsList() 来返回包含列名字符串的数组。编辑:我已经确认数组 columnsList[] 实际上是使用 for 循环和 println 接收列名。只是想不通为什么返回仍然充满了空值

还添加了我正在使用的所有代码。ListTables() 方法非常相似并且存在相同的问题,但我认为如果我修复了一个,另一个也将得到修复

预先感谢您的任何帮助

4

2 回答 2

0

周末后我开始工作,代码终于决定工作了。

于 2013-07-24T14:36:34.277 回答
0

我没有看到任何明显的错误。我将调试代码并检查 while(rs.next()) 循环中的结果集。

以下教程有一个“列出表格”的代码示例。

http://tutorials.jenkov.com/jdbc/databasemetadata.html

您的代码有两个不同之处:

  • 结果集列按索引访问
  • columnPattern 作为 null 传递。

可能“COLUMN_NAME”不是mysql用于列名的列。

public static String[] listColumns(){
    String[] columnsList = new String[2];
    try{    

        columnsList[0] = "0";

        if (true) throw new RuntimeException();

        columnsList[1] = "1";

        return columnsList;         
    } catch(Exception ex) {
        //a println to check if the catch is filling up the array with null
        System.out.println("i screwed up");
        System.out.println(ex);         
        return columnsList;
    }
}

public static void main(String[] args) {
    System.out.println(Arrays.asList(listColumns()));
}

此代码打印:

  i screwed up 
  java.lang.RuntimeException 
  [0, null] 
于 2013-07-19T18:29:52.763 回答