首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

Java/jdbc连接数据库预加工只能查询一条数据

2012-12-20 
Java/jdbc连接数据库预处理只能查询一条数据?今天在写一个小项目的时候连接数据库读取数据生成栏目,开始写

Java/jdbc连接数据库预处理只能查询一条数据?

今天在写一个小项目的时候连接数据库读取数据生成栏目,开始写了个这样的方法:但是每次只能读取一行数据,明明有好几条数据,其代码如下:

public static List<Programa> getPrograma(int qx) throws SQLException{Connection conn = null;PreparedStatement pstmt = null;ResultSet rs = null;List<Programa> list = new ArrayList<Programa>();Programa programa = null;try {conn=connectionFactory.getConnection();String sql = "";if (qx == 1) {//for adminsql="select pId,pName,pURL from programaTable where -1<?";}else {//for user :QX == 0sql="select pId,pName,pURL from programaTable where QX=?";}pstmt=conn.prepareStatement(sql);pstmt.setInt(1, qx);rs=pstmt.executeQuery();if(rs.next()){System.out.println("000000000");programa = new Programa();programa.setId(rs.getInt(1));programa.setName(rs.getString(2));programa.setUrl(rs.getString(3));list.add(programa);}rs.close();pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();} return list;}

 

我就纳闷了,以前也写过JDBC连数据库的,我开始还以为是MYSQL的问题,后来我写过了一个方法,能把数据全部正确的读出来:代码如下:

public static List<Programa> getPrograma2(int qx) throws SQLException{Connection con = null;Statement stmt = null;ResultSet rs = null;List<Programa> list = new ArrayList<Programa>();Programa programa = null;try {con = connectionFactory.getConnection();String sql = "select pId,pName,pURL from programaTable";stmt = con.createStatement();rs = stmt.executeQuery(sql);while (rs.next()) {int col1 = rs.getInt(1);String col2 = rs.getString(2);String col3 = rs.getString(3);programa = new Programa();programa.setId(col1);programa.setName(col2);programa.setUrl(col3);list.add(programa);}// 关闭数据库连接rs.close();stmt.close();con.close();} catch (Exception e) {e.printStackTrace();}return list;}


后来看查一下,连接数据库的配置文件,原来配置文件将自动提交设置为true,

总结:如果设置自动提交为false,用预处理连接数据库,只能查询一条数据(不管rs = stmt.executeQuery(sql);后面是否写上上con.commit();)

                                                      但是不用预处理能查到该查到的所有数据(不用写自动提交)

              如果设置自动提交为true ,用预处理连接数据库,只能查询一条数据(rs = stmt.executeQuery(sql);后面不能写上上con.commit();否则报错)

                                                      但是不用预处理能查到该查到的所有数据(不用写自动提交)

 

于是就出现一个问题,难道用预处理只能查到一条数据吗?????

 

 

 

 

 

热点排行