MySQL JDBC返回0结果

时间:2012-06-14 11:41:18

标签: java mysql jdbc

这似乎是一个非常基本的问题,但我找不到任何解决方案。 我有以下代码:

package com.test.db.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCConnect
{
private Connection conn = null;
private final String uname = "root";
private final String passwd = "test@123";
private String url = "jdbc:mysql://127.0.0.1:3306/TrainDB";
private final String className = "com.mysql.jdbc.Driver";

public void initConnection()
{
    try
    {
        if(this.conn == null || this.conn.isClosed())
        {
            try
            {
                Class.forName (className).newInstance ();
                this.conn = DriverManager.getConnection(url, uname, passwd);
                System.out.println("database connection established.");
            }
            catch(SQLException sqe)
            {
                sqe.printStackTrace();
            }
            catch (InstantiationException e) 
            {
                e.printStackTrace();
            } 
            catch (IllegalAccessException e) 
            {
                e.printStackTrace();
            } 
            catch (ClassNotFoundException e) 
            {
                e.printStackTrace();
            }

        }
    }
    catch(SQLException sqle)
    {
        sqle.printStackTrace();
    }
    //return this.conn;
}

public void disconnect()
{
    if (conn != null)
        {
            try
            {
                conn.close ();
                System.out.println ("Database connection terminated");
            }
            catch (Exception e) { /* ignore close errors */ }
        }

}

public void insertData(String sql)
{
    PreparedStatement s;
    try
    {

        if(conn == null || conn.isClosed())
        {
            initConnection();
        }
        s = conn.prepareStatement(sql);
        int count = s.executeUpdate ();
        s.close ();
        System.out.println (count + " rows were inserted");
    } 
    catch (SQLException e) 
    {
        e.printStackTrace();
        if (conn != null)
        {
            try
            {
                conn.close ();
                System.out.println ("Database connection terminated");
            }
            catch (Exception se) { /* ignore close errors */ }
        }
    }

}

public ResultSet query(String sql)
{
    Statement s = null;
    try
    {
        if(this.conn == null || this.conn.isClosed())
        {
            initConnection();
        }

                    s = conn.createStatement();
        s.executeQuery(sql);
        ResultSet rs = s.getResultSet();
        System.out.println("lets see " + rs.getFetchSize());
        return rs;
    }
    catch(SQLException sq)
    {
        System.out.println("Error in query");
        return null;
    }
    finally
    {
        try {
            s.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
}

我在另一个类中使用JDBCConnect:

import java.sql.ResultSet;
import java.sql.SQLException;

public class traininfo
{

public static void main(String[] args)
{
    JDBCConnect jdbcConn = new JDBCConnect();

    String sql = "SELECT id FROM testtable";
    ResultSet rs = jdbcConn.query(sql);
    try {
        System.out.println(rs.getFetchSize());
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(rs != null)
    {
        try
        {
            while(rs.next())
            {
                System.out.println(rs.getString("id"));
            }
            rs.close();
        }
        catch(SQLException sqe)
        {

        }
    }
    jdbcConn.disconnect();
}
}

我没有使用并发调用进行插入和读取。如果我在mysql-workbench(客户端)中使用相同的查询,我得到了正确的结果,但使用提到的代码,我得到了

database connection established.
lets see 0
0
Database connection terminated

请告诉我我缺少的东西?

3 个答案:

答案 0 :(得分:2)

很可能是因为您在使用Statement之前关闭了ResultSet。奇怪的是,它不会抛出异常,但无论如何这都不正确。

根据Statement.close method JavaDoc

  

当Statement对象关闭时,它的当前ResultSet对象(如果存在)也将关闭。

我建议使用某种回调来在ResultSet关闭之前检索结果,例如:

public <T> T query(String sql, IResultSetHandler<T> resultSetHandler ) throws SQLException {
    Statement statement = null;
    try {
        statement = connection.createStatement();
        final ResultSet rs = connection.executeQuery(sql);
        final T result = resultSetHandler.handle(rs);
        return result;
    } finally {
        if(statement != null) {
            statement.close();
        }
    }
}

public interface IResultSetHandler<T> {
    T handle(ResultSet rs);
}

public static void main(String[] args) {
    JDBCConnect jdbcConn = new JDBCConnect();
    List<String> ids = jdbcConn.query(sql, new IResultSetHandler<List<String>>() {
        public List<String> handle(ResultSet rs) {
            List<String> ids = new ArrayList<String>();
            while(rs.next()) {
                ids.add(rs.getString("id"));
            }
            return ids;
        }
    });
}

或者使用commons apache dbutils库,它完全相同。

答案 1 :(得分:1)

ResultSet.getFetchSize()可让您知道连接一次获取的最大行数。您可以使用ResultSet.setFetchSize(int)进行设置。另见the official documentation。它不会告诉您总共会有多少行。如果获取大小为零,则JDBC自行决定。

除此之外,请参阅Yura的答案,该答案解决了问题的核心。

答案 2 :(得分:0)

可能是因为你从不调用InsertRows,因为它从未显示“插入了X行”