0

我不擅长 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 语句的行。

4

2 回答 2

2

试试Oracle 的本教程。它简单明了。

会是这样的

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..
}
于 2013-07-19T06:14:33.810 回答
2

这是代码

    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 ......驱动程序将随着您使用的数据库而改变。

希望这可以帮助。

于 2013-07-19T06:29:18.580 回答