如何将表数据从数据库打印到Java控制台?

时间:2013-07-19 06:13:01

标签: java mysql

我对Java并不擅长我只学习了基础知识,而且它仍然有点新鲜。我想知道有人如何从表中打印一行到Java控制台。

try {
    statement = con.prepareStatement(
                "SELECT * FROM users WHERE Username ='" + 
                LOGIN_UsernameField.getText() + "' AND Password ='" +
                LOGIN_PasswordField.getPassword() + "'");
    System.out.println ();
}

我所知道的那个system.out.println当然不起作用,我需要更换它来打印出来自它上面的SQL语句的行。

2 个答案:

答案 0 :(得分:2)

从Oracle尝试this tutorial。这很简单直接。

就像这样

try{
        statement = con.prepareStatement(
                "SELECT * FROM users WHERE Username = ? AND Password =?");
        statement.setString(0,LOGIN_UsernameField.getText());
        statement.setString(0,LOGIN_PasswordField.getPassword());
        ResultSet rs = statement.execute();
        while(rs.next()){
           System.out.println("UserName:"+rs.getString("Username")+"\nPassword:"+rs.getString("Password"));
       } 
}catch(){
 //handle exceptions
}finally{
 //close statements, statement and resultset here..
}

答案 1 :(得分:1)

这是代码

    System.out.println("-------- MySQL JDBC Connection Testing ------------");


    Connection connection = null;

    try {
        connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/testDb", "userName", "Password");
    } catch (SQLException e) {
        for(Throwable ex : e) {
            System.err.println("Error occurred " + ex);
        }
        e.printStackTrace();
    }

    if (connection != null) {
        System.out.println("Connected to database!");
    } else {
        System.out.println("Failed to make connection!");
    }

    try {
        Statement stmt = connection.createStatement();
        String query = "select * from person ;";
    //person is the table name
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String name = rs.getObject(1).toString();
            String gender = rs.getObject(2).toString();
            System.out.println("Name of the person is " + name + " and his gender is " + gender);
    //Person table has name and gender column

        }
    } catch (SQLException e) {
        e.printStackTrace();
        for(Throwable ex : e) {
            System.err.println("Error occurred " + ex);
        }
        System.out.println("Error in fetching data");
    }

注意:我使用JDBC 4附带的Java 7,因此无需明确提供驱动程序。编译器将自动从类路径中获取它。您可以下载MySqlConnector.jar并将其放在类路径中。如果您不使用Java 7,则必须使用Class.forName()显式加载驱动程序。当然我正在使用MySql ...驱动程序将随您使用的数据库而改变。

希望这有帮助。