简体   繁体   English

Java中的SQL结果集

[英]SQL resultset in Java

Hello I just started with SQL in Java ( actually also started not long ago with Java also.. ) and I created a class to get connected with a MySQL database and it all worked well. 您好我刚刚开始使用Java中的SQL(实际上也是不久前也开始使用Java也是如此......)我创建了一个类来连接MySQL数据库并且一切运行良好。

Now I have a question for the getting the result. 现在我有一个问题来获得结果。

in PHP I would do something like 在PHP中,我会做类似的事情

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

In Java I tried to create something similar to this but I don;t know if im going the right way or that it should be much different or whatever.. here is what i've made ( see getResultList method ) 在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;
    }
}

ResultSetMetaData is an interface which provides all the information about the ResultSet like all the Column names, types, length etc of generated ResultSet. ResultSetMetaData是一个接口,它提供有关ResultSet的所有信息,如生成的ResultSet的所有列名,类型,长度等。

Just use that interface. 只需使用该界面。 For more information and documentation about API just visit Oracle website. 有关API的更多信息和文档,请访问Oracle网站。

Try below code. 试试下面的代码。 Change query, url, user, password with desired query and credentials. 使用所需的查询和凭据更改查询,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());


 }  
  }

For documentation and api please visit below oracle site. 有关文档和api,请访问下面的oracle站点。

Documentation and api of ResultSetMetaData ResultSetMetaData的文档和API

in your while loop you have used assignment operator. 在你的while循环中你使用了赋值运算符。 rs.next() returns true or false rs.next()返回true或false

 while(row=rs.next()) 
{}

you can simply say, 你可以简单地说,

while(rs.next()) 
{}

its very easily done in java you are good to this code you can guide and see example in this link 它很容易在java中完成你很好的代码,你可以指导和看到这个链接中的示例

http://www.roseindia.net/answers/viewqa/Java-Beginners/3488-mysql-with-jsp.html http://www.roseindia.net/answers/viewqa/Java-Beginners/3488-mysql-with-jsp.html

public void connectToAndQueryDatabase(String username, String password) {

    Connection con = DriverManager.getConnection(
                         "jdbc:myDriver:myDatabase",
                         username,
                         password);

    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");

    while (rs.next()) {
        int x = rs.getInt("a");
        String s = rs.getString("b");
        float f = rs.getFloat("c");
    }
}

The best place to understand how to use JDBC is the JDBC tutorial from Oracle website. 了解如何使用JDBC的最佳位置是Oracle网站的JDBC教程

For understanding how to retrieve values from a resultset look at this part of the tutorial. 有关如何从结果集中检索值的信息,请参阅本教程的这一部分。

A ResultSet object is a table of data representing a database result set, which is usually generated by executing a statement that queries the database. ResultSet对象是表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。

You access the data in a ResultSet object through a cursor. 您可以通过游标访问ResultSet对象中的数据。 Note that this cursor is not a database cursor. 请注意,此游标不是数据库游标。 This cursor is a pointer that points to one row of data in the ResultSet. 此游标是指向ResultSet中一行数据的指针。 Initially, the cursor is positioned before the first row. 最初,光标位于第一行之前。 The method ResultSet.next moves the cursor to the next row. ResultSet.next方法将光标移动到下一行。 This method returns false if the cursor is positioned after the last row. 如果光标位于最后一行之后,则此方法返回false。 This method repeatedly calls the ResultSet.next method with a while loop to iterate through all the data in the ResultSet. 此方法使用while循环重复调用ResultSet.next方法以迭代ResultSet中的所有数据。

The ResultSet interface declares getter methods (for example, getBoolean and getLong) for retrieving column values from the current row. ResultSet接口声明getter方法(例如,getBoolean和getLong),用于从当前行检索列值。 You can retrieve values using either the index number of the column or the alias or name of the column. 您可以使用列的索引号或列的别名或名称来检索值。 The column index is usually more efficient. 列索引通常更有效。 Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once. 列从1开始编号。为了获得最大的可移植性,每行中的结果集列应按从左到右的顺序读取,每列应只读一次。

You have a lot of methods in the ResultSet for dealing with it. ResultSet中有很多方法可以处理它。

If you need to to loop through it, just use 如果你需要循环它,只需使用

rs.next();

If you need to get a column by its alias: 如果您需要通过别名获取列:

rs.getString("alias");
rs.getFloat("other_alias");
// or by column index
rs.getString(3);

You also have an utility class for extracting information about the result set like the number of columns and their names: 您还有一个实用程序类,用于提取有关结果集的信息,如列数及其名称:

rs.getMetaData();

Make sure you close your connection after you're done with it. 确保在完成连接后关闭连接。

Just past your result set to below method and it will return desired result you are looking for. 刚刚将结果集转到下面的方法,它将返回您正在寻找的所需结果。

public List<Map<String, Object>> getResultsList(ResultSet rs) throws SQLException
{
    ResultSetMetaData metadata = rs.getMetaData();
    int columns = metadata.getColumnCount();

    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    while (rs.next())
    {
        Map<String, Object> row = new HashMap<String, Object>(columns);
        for (int i = 1; i <= columns; ++i)
        {
            row.put(metadata.getColumnName(i), rs.getObject(i));
        }
        results.add(row);
    }

    return results;
}

to deal with Database Java provides java.sql.* package. 处理Database Java提供了java.sql。*包。 You need to read the java docs for this API and and learn their usages. 您需要阅读此API的Java文档并了解它们的用法。 You can apply best logic and trick based on your business requirement only when you know the usages of java.sql.* package. 只有在了解java.sql。*包的用法时,才能根据业务需求应用最佳逻辑和技巧。

I suggest you to go through the oracle docs first then come to community if you stuck somewhere. 我建议你首先通过oracle文档,然后如果你卡在某个地方就来社区。

Go through the ResultSetMetaData Interface. 浏览ResultSetMetaData接口。 I guess this interface is answer to your question. 我想这个界面是你问题的答案。

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSetMetaData.html http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSetMetaData.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM