Java中的SQL结果集

您好我刚开始用Java编写Java(实际上也是不久前用Java开始的……)
我创建了一个与MySQL数据库连接的类,它运行良好.

现在我有一个问题来获得结果.

PHP中,我会做类似的事情

While($row = mysql_fetch_assoc()) {
  echo $row['rowname'];
}

在Java中我尝试创建类似于此的东西,但我不知道我是以正确的方式还是它应该有很大的不同或者其他什么……这就是我所做的(参见getResultList方法)

public class MysqlConnect{

     private String query;
     private ResultSet rs;

    public void connectToAndQueryDatabase(String database, String username, String password) throws SQLException {

            Connection con = null;
            try {
                con = DriverManager.getConnection(
                                     "jdbc:mysql://localhost:3306/" + database,
                                     username,
                                     password);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            Statement stmt = con.createStatement();
            rs = stmt.executeQuery(query);
    }

    public void setQuery(String query) {

        this.query = query;

    }

    public List getResultList() {
        ArrayList<HashMap> row = new ArrayList<HashMap>(); 
        while(row = rs.next()) {

        }

        return rs;
    }
}
最佳答案
试试下面的代码.使用所需的查询和凭据更改查询,URL,用户,密码.

public static void main(String args[]) {

String url = "database url";
Connection con;
String query = "Your select query here";
Statement stmt;

try {
  Class.forName("Full driver class name");

} catch(java.lang.ClassNotFoundException e) {
  System.err.print("ClassNotFoundException: ");
  System.err.println(e.getMessage());
}

try {
  con = DriverManager.getConnection(url, 
               "user", "password");

  stmt = con.createStatement();              

  ResultSet rs = stmt.executeQuery(query);
  ResultSetMetaData rsmd = rs.getMetaData();
  int numberOfColumns = rsmd.getColumnCount();
  int rowCount = 1;
  while (rs.next()) {
    System.out.println("Row " + rowCount + ":  ");
    for (int i = 1; i <= numberOfColumns; i++) {
      System.out.print("   Column " + i + ":  ");
      System.out.println(rs.getString(i));
    }
    System.out.println("");
    rowCount++;
  }
  stmt.close();
  con.close();

} catch(SQLException ex) {
  System.err.print("SQLException: ");
  System.err.println(ex.getMessage());


 }  
  }

有关文档和api,请访问下面的oracle站点.

Documentation and api of ResultSetMetaData

转载注明原文:Java中的SQL结果集 - 代码日志