【问题标题】:Cant get data throw Result Set in connected Java with SQL无法通过 SQL 连接的 Java 中的结果集获取数据
【发布时间】:2014-05-27 01:04:08
【问题描述】:

这里我不能进入 while(rs.next()){.....} 语句。你看,我尝试准备简单的语句,并尝试在 println 中打印单词“data”以检查我是否在 while 语句中,但没有打印任何内容:(

              Connection conn = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String connectionUrl = "jdbc:sqlserver://FIO\\SQLEXPRESS;" +
        "databaseName=Feedback;integratedSecurity=true";

        conn = DriverManager.getConnection(connectionUrl);
        //String sqlStmt = "SELECT SubjectName, Semester, Year, TrainerFirstName, TrainerLastName, StudentFirstName,StudentLastName, Answer FROM Feedback.dbo.quest WHERE TrainerFirstName='?' AND TrainerLastName='?' AND Semester=? AND Year=?";
        String sqlStmt = "SELECT * FROM Feedback.dbo."+quest;
                    System.out.println("SQL Statement:\n\t" + sqlStmt);
        prepStmt = conn.prepareStatement(sqlStmt);


        //prepStmt.setString(1,ffname);
                    //prepStmt.setString(2, llname);
                    //prepStmt.setString(3, sem);
                    //prepStmt.setString(4,yea);



        rs = prepStmt.executeQuery(sqlStmt);
        while (rs.next()) {

                        System.out.println(rs.getString(1));

                        System.out.println("data:"+rs.getString(1) + rs.getInt(2)+rs.getInt(3)+rs.getString(4)+rs.getString(5)+rs.getString(6)+rs.getString(7)+rs.getString(8));

                        /*String id = rs.getString("id");
            String firstName = rs.getString("first_name");
            String lastName = rs.getString("last_name");
            System.out.println("ID: " + id + ", First Name: " + firstName + ", Last Name: " + lastName);*/
        }
    } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException e) {
           }

它只打印了这个:

SQL 语句: 从 Feedback.dbo.Question1 中选择 * 绑定变量集之前的预处理语句: SQLServerPreparedStatement:1 绑定变量设置后的预处理语句: SQLServerPreparedStatement:1 构建成功(总时间:20 秒)

看来,while 语句被省略了。

非常感谢。

【问题讨论】:

    标签: java sql database-connection resultset


    【解决方案1】:

    Prepare 语句必须链接到变量,然后执行。

    如果您没有要绑定的变量,请使用Statement,然后使用executeQuery,而不是PrepareStatement

    下面的示例代码显示了StatementPrepareStatement 的使用情况。

    import java.sql.*;
    
    public class TestSql {
        public static void main(String[] args) {
            Connection con = null;
            PreparedStatement ps = null;
            Statement s = null;
            ResultSet rs = null;
            try {
                try {
                    System.out.println("Buscando el driver JDBC...");
                    Class.forName("com.mysql.jdbc.Driver"
                    // "org.postgresql.Driver"
                            // "oracle.jdbc.driver.OracleDriver"
                            // "com.microsoft.sqlserver.jdbc.SQLServerDriver"
                            // "org.firebirdsql.jdbc.FBDriver"
                            ).newInstance();
                    System.out.println("...Encontró el driver JDBC");
                } catch (Exception e) {
                    System.out.println("No pudo encontrar el driver JDBC !!!!");
                    e.printStackTrace(System.out);
                    return;
                }
                try {
                    System.out.println("Connectando a la base de datos...");
                    con = DriverManager
                            .getConnection("jdbc:mysql://localhost/curso?user=curso&password=123"
                            // "jdbc:postgresql://localhost/curso:5432","postgres","123"
                            // "jdbc:oracle:thin:@192.168.0.10:1521/XE","curso","123"
                            // "jdbc:sqlserver://192.168.0.100:1433/database=curso/user=curso/password=123"
                            // "jdbc:firebirdsql:127.0.0.1:C:/firebird/data/curso.gdb","curso","123"
                            );
                    System.out.println("...Connectado a la base de datos");
                } catch (Exception e) {
                    System.out
                            .println("No pudo conectarse a la base de datos !!!!");
                    e.printStackTrace(System.out);
                    return;
                }
                try {
                    System.out
                            .println("Lista de empleados con salario inferior a $30,000");
                    s = con.createStatement();
                    rs = s
                            .executeQuery("select concat(first_name,' ',last_name) as full_name from employee where salary < 30000");
                    // "select first_name||' '||last_name as full_name from employee where salary < 30000");
                    while (rs.next()) {
                        System.out.println(rs.getString("full_name"));
                    }
                } catch (java.sql.SQLException e) {
                    System.out.println("Unable to step thru results of query");
                    showSQLException(e);
                    return;
                }
                try {
                    System.out
                            .println("===============================================");
                    System.out
                            .println("Lista de empleados con salario entre $30,000 y $40,000");
                    ps = con
                            .prepareStatement("select concat(first_name,' ',last_name) as full_name from employee where salary between ? and ?");
                    // "select first_name||' '||last_name as full_name from employee where salary between ? and ?");
                    ps.setInt(1, 30000);
                    ps.setInt(2, 40000);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        System.out.println(rs.getString("full_name"));
                    }
                } catch (java.sql.SQLException e) {
                    System.out.println("Unable to submit a static SQL query.");
                    showSQLException(e);
                    return;
                }
            } finally {
                System.out.println("Cerrando la conexion a la base de datos.");
                try {
                    if (rs != null) {
                        rs.close();
                    }
                } catch (java.sql.SQLException e) {
                    showSQLException(e);
                }
                try {
                    if (ps != null) {
                        ps.close();
                    }
                } catch (java.sql.SQLException e) {
                    showSQLException(e);
                }
                try {
                    if (con != null) {
                        con.close();
                    }
                } catch (java.sql.SQLException e) {
                    showSQLException(e);
                }
                System.out.println("Fin");
            }
        }
    
        private static void showSQLException(java.sql.SQLException e) {
            java.sql.SQLException next = e;
            while (next != null) {
                System.out.println(next.getMessage());
                System.out.println("Error Code: " + next.getErrorCode());
                System.out.println("SQL State: " + next.getSQLState());
                next = next.getNextException();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2012-11-21
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      相关资源
      最近更新 更多