无法从结果集中检索值 (jdbc)

发布于 2024-12-07 13:29:05 字数 1061 浏览 0 评论 0原文

ResultSet rs = stmt.executeQuery(query); 之后,代码不会执行。因此,变量不会从结果集中获取值。有人能帮我解决这个问题吗?

public User storeTempDetails(String s1){ 
Statement stmt = null;
String query = "select username, account_no,name from accounts where username = ?";
try {
  connection = DriverManager.getConnection(DBurl, DBusername, DBpassword);
  System.out.println("Database connected!");
  stmt = connection.createStatement();
  ResultSet rs = stmt.executeQuery(query);
  System.out.println("this line is not printed");
  while (rs.next()) {
    userName = rs.getString("username");
    accountNo = rs.getString("account_no");
    name = rs.getString("name");System.out.println("ss"+accountNo);
  }
} catch (SQLException e ) {
  throw new RuntimeException("Cannot connect the database!", e);
} finally {
   User userObj=new User(userName,accountNo,name);
        System.out.println("Closing the connection.");
        if (connection != null) try { connection.close(); }
        catch (SQLException ignore) {}
        return userObj;
}

}

After ResultSet rs = stmt.executeQuery(query); , the code does not execute. Thus, the variables do not get the values from the result set . Can anybody help me resolve this ?

public User storeTempDetails(String s1){ 
Statement stmt = null;
String query = "select username, account_no,name from accounts where username = ?";
try {
  connection = DriverManager.getConnection(DBurl, DBusername, DBpassword);
  System.out.println("Database connected!");
  stmt = connection.createStatement();
  ResultSet rs = stmt.executeQuery(query);
  System.out.println("this line is not printed");
  while (rs.next()) {
    userName = rs.getString("username");
    accountNo = rs.getString("account_no");
    name = rs.getString("name");System.out.println("ss"+accountNo);
  }
} catch (SQLException e ) {
  throw new RuntimeException("Cannot connect the database!", e);
} finally {
   User userObj=new User(userName,accountNo,name);
        System.out.println("Closing the connection.");
        if (connection != null) try { connection.close(); }
        catch (SQLException ignore) {}
        return userObj;
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离笑几人歌 2024-12-14 13:29:05

从这样的事情开始。这些实用程序类将使您在开始使用 JDBC 时变得更加轻松:

package persistence;

import java.sql.*;
import java.util.*;

/**
 * util.DatabaseUtils
 * User: Michael
 * Date: Aug 17, 2010
 * Time: 7:58:02 PM
 */
public class DatabaseUtils
{
    private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
    private static final String DEFAULT_USERNAME = "username";
    private static final String DEFAULT_PASSWORD = "password";
/*
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
    private static final String DEFAULT_USERNAME = "pgsuper";
    private static final String DEFAULT_PASSWORD = "pgsuper";
*/
/*
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
    private static final String DEFAULT_USERNAME = "party";
    private static final String DEFAULT_PASSWORD = "party";
*/

    public static void main(String[] args)
    {
        long begTime = System.currentTimeMillis();

        String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
        String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
        String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
        String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);

        Connection connection = null;

        try
        {
            connection = createConnection(driver, url, username, password);
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println(meta.getDatabaseProductName());
            System.out.println(meta.getDatabaseProductVersion());

            String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
            System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));

            connection.setAutoCommit(false);
            String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
            List parameters = Arrays.asList( "Foo", "Bar" );
            int numRowsUpdated = update(connection, sqlUpdate, parameters);
            connection.commit();

            System.out.println("# rows inserted: " + numRowsUpdated);
            System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
        }
        catch (Exception e)
        {
            rollback(connection);
            e.printStackTrace();
        }
        finally
        {
            close(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("wall time: " + (endTime - begTime) + " ms");
        }
    }

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
    {
        Class.forName(driver);

        if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
        {
            return DriverManager.getConnection(url);
        }
        else
        {
            return DriverManager.getConnection(url, username, password);
        }
    }

    public static void close(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }


    public static void close(Statement st)
    {
        try
        {
            if (st != null)
            {
                st.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs)
    {
        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.rollback();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
    {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        try
        {
            if (rs != null)
            {
                ResultSetMetaData meta = rs.getMetaData();
                int numColumns = meta.getColumnCount();
                while (rs.next())
                {
                    Map<String, Object> row = new HashMap<String, Object>();
                    for (int i = 1; i <= numColumns; ++i)
                    {
                        String name = meta.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(name, value);
                    }
                    results.add(row);
                }
            }
        }
        finally
        {
            close(rs);
        }

        return results;
    }

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        List<Map<String, Object>> results = null;

        PreparedStatement ps = null;
        ResultSet rs = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            rs = ps.executeQuery();
            results = map(rs);
        }
        finally
        {
            close(rs);
            close(ps);
        }

        return results;
    }

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        int numRowsUpdated = 0;

        PreparedStatement ps = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            numRowsUpdated = ps.executeUpdate();
        }
        finally
        {
            close(ps);
        }

        return numRowsUpdated;
    }
}

考虑到这些实用程序,我将如何编写它。我可能会将 User 放在 model 包中,而 UserDaoImpl 将是其自己的 .java 文件中的公共类。我只是懒:

package persistence;

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

/**
 * UserDao
 * @author Michael
 * @since 10/2/11
 */
public interface UserDao
{
    User find(String username);
}

class UserDaoImpl implements UserDao {

    public static final String SELECT_USER_BY_USERNAME = "select username, account_no,name from accounts where username = ?";

    private Connection connection;

    UserDaoImpl(Connection connection)
    {
        this.connection = connection;
    }

    public User find(String username)
    {
        User user = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try
        {
            ps = this.connection.prepareStatement(SELECT_USER_BY_USERNAME);
            ps.setString(1, username);
            rs = ps.executeQuery();
            while (rs.next()) {
                String account = rs.getString("account_no");
                String name = rs.getString("name");
                user = new User(name, username, account);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace(); 
        }
        finally
        {
            DatabaseUtils.close(rs);
            DatabaseUtils.close(ps);
        }

        return user;
    }
}

class User {
    private final String name;
    private final String username;
    private final String account;

    User(String name, String username, String account)
    {
        this.name = name;
        this.username = username;
        this.account = account;
    }

    public String getName()
    {
        return name;
    }

    public String getUsername()
    {
        return username;
    }

    public String getAccount()
    {
        return account;
    }

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        sb.append("User");
        sb.append("{name='").append(name).append('\'');
        sb.append(", username='").append(username).append('\'');
        sb.append(", account='").append(account).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

Start with something like this. These are utility classes that will make your life easier when you're starting off with JDBC:

package persistence;

import java.sql.*;
import java.util.*;

/**
 * util.DatabaseUtils
 * User: Michael
 * Date: Aug 17, 2010
 * Time: 7:58:02 PM
 */
public class DatabaseUtils
{
    private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
    private static final String DEFAULT_USERNAME = "username";
    private static final String DEFAULT_PASSWORD = "password";
/*
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
    private static final String DEFAULT_USERNAME = "pgsuper";
    private static final String DEFAULT_PASSWORD = "pgsuper";
*/
/*
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
    private static final String DEFAULT_USERNAME = "party";
    private static final String DEFAULT_PASSWORD = "party";
*/

    public static void main(String[] args)
    {
        long begTime = System.currentTimeMillis();

        String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
        String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
        String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
        String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);

        Connection connection = null;

        try
        {
            connection = createConnection(driver, url, username, password);
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println(meta.getDatabaseProductName());
            System.out.println(meta.getDatabaseProductVersion());

            String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
            System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));

            connection.setAutoCommit(false);
            String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
            List parameters = Arrays.asList( "Foo", "Bar" );
            int numRowsUpdated = update(connection, sqlUpdate, parameters);
            connection.commit();

            System.out.println("# rows inserted: " + numRowsUpdated);
            System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
        }
        catch (Exception e)
        {
            rollback(connection);
            e.printStackTrace();
        }
        finally
        {
            close(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("wall time: " + (endTime - begTime) + " ms");
        }
    }

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
    {
        Class.forName(driver);

        if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
        {
            return DriverManager.getConnection(url);
        }
        else
        {
            return DriverManager.getConnection(url, username, password);
        }
    }

    public static void close(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }


    public static void close(Statement st)
    {
        try
        {
            if (st != null)
            {
                st.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs)
    {
        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.rollback();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
    {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        try
        {
            if (rs != null)
            {
                ResultSetMetaData meta = rs.getMetaData();
                int numColumns = meta.getColumnCount();
                while (rs.next())
                {
                    Map<String, Object> row = new HashMap<String, Object>();
                    for (int i = 1; i <= numColumns; ++i)
                    {
                        String name = meta.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(name, value);
                    }
                    results.add(row);
                }
            }
        }
        finally
        {
            close(rs);
        }

        return results;
    }

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        List<Map<String, Object>> results = null;

        PreparedStatement ps = null;
        ResultSet rs = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            rs = ps.executeQuery();
            results = map(rs);
        }
        finally
        {
            close(rs);
            close(ps);
        }

        return results;
    }

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
    {
        int numRowsUpdated = 0;

        PreparedStatement ps = null;

        try
        {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters)
            {
                ps.setObject(++i, parameter);
            }

            numRowsUpdated = ps.executeUpdate();
        }
        finally
        {
            close(ps);
        }

        return numRowsUpdated;
    }
}

Given those utilities, here's how I might write it. I'd probably put User in a model package, and UserDaoImpl would be a public class in its own .java file. I'm just being lazy:

package persistence;

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

/**
 * UserDao
 * @author Michael
 * @since 10/2/11
 */
public interface UserDao
{
    User find(String username);
}

class UserDaoImpl implements UserDao {

    public static final String SELECT_USER_BY_USERNAME = "select username, account_no,name from accounts where username = ?";

    private Connection connection;

    UserDaoImpl(Connection connection)
    {
        this.connection = connection;
    }

    public User find(String username)
    {
        User user = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try
        {
            ps = this.connection.prepareStatement(SELECT_USER_BY_USERNAME);
            ps.setString(1, username);
            rs = ps.executeQuery();
            while (rs.next()) {
                String account = rs.getString("account_no");
                String name = rs.getString("name");
                user = new User(name, username, account);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace(); 
        }
        finally
        {
            DatabaseUtils.close(rs);
            DatabaseUtils.close(ps);
        }

        return user;
    }
}

class User {
    private final String name;
    private final String username;
    private final String account;

    User(String name, String username, String account)
    {
        this.name = name;
        this.username = username;
        this.account = account;
    }

    public String getName()
    {
        return name;
    }

    public String getUsername()
    {
        return username;
    }

    public String getAccount()
    {
        return account;
    }

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        sb.append("User");
        sb.append("{name='").append(name).append('\'');
        sb.append(", username='").append(username).append('\'');
        sb.append(", account='").append(account).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
み格子的夏天 2024-12-14 13:29:05

有一个异常抛出。但由于 finally 块中的 return,该异常永远不会发生。谷歌搜索“java”、“return”和“finally”,你会感觉到这有多糟糕

修复代码并向我们展示堆栈跟踪。

There is an exception thrown. But that exception will never get anywhere, because of the return in the finally block. Google for "java", "return" and "finally" and you will get a feeling how bad that is.

Fix the code and show us the stacktrace.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文