有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mysql Java应用程序无法在控制台窗口中显示结果

我正在学习java。我正在尝试从mysql数据库读取数据并在控制台窗口中显示记录。但问题是,当我成功地运行代码,但没有显示记录时

这是我的联系课

package halifaxapp;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
/**
 *
 * @author Khundokar Nirjor
 */
public class MySQLJDBCUtil {
  public static Connection getConnection() throws SQLException {
        Connection conn = null;

        try (FileInputStream f = new FileInputStream("db.properties")) {

            // load the properties file
            Properties pros = new Properties();
            pros.load(f);

            // assign db parameters
            String url = pros.getProperty("jdbc:mysql://localhost:8081/mysqljdbc");
            String user = pros.getProperty("root");
            String password = pros.getProperty("9090");

            // create a connection to the database
            conn = DriverManager.getConnection(url, user, password);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }

}

这里是主要的方法

package halifaxapp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 *
 * @author Khundokar Nirjor
 */
public class HalifaxApp {


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        // 
        String sql = "SELECT first_name, last_name, email " +
                     "FROM candidates";

        try (Connection conn = MySQLJDBCUtil.getConnection();
             Statement stmt  = conn.createStatement();
             ResultSet rs    = stmt.executeQuery(sql)) {

            // loop through the result set
            while (rs.next()) {
                System.out.println(rs.getString("first_name") + "\t" + 
                                   rs.getString("last_name")  + "\t" +
                                   rs.getString("email"));

            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

这是我运行应用程序时的屏幕截图。 enter image description here


共 (1) 个答案

  1. # 1 楼答案

    属性文件将是一个名称/值对,如

    url=jdbc:mysql://localhost:8081/mysqljdbc
    user=root
    

    然后你可以用like

    String url = pros.getProperty("url");
    

    此外,当您捕获到异常时,请执行以下操作:

    ex.printStackTrace();
    

    而不是

    System.out.println(ex.getMessage());