必备sql语句

来源:互联网 发布:淘宝上做什么生意赚钱 编辑:程序博客网 时间:2024/05/17 04:14

 1.读出数据库表中的字段名
ResultSet  rs = test.selectSql("SELECT * FROM datainfo");  
java.sql.ResultSetMetaData md=rs.getMetaData();   //读出数据库的字段名
   int nColumn=md.getColumnCount();   //字段总数
   for(int i=0;i<nColumn;i++)
  { 
  System.out.println(md.getColumnLabel(i+1));       //md.getColumnLabel(n)n是从1开始的,打印每个字段
  }

2.查询某个时间段内的数据
String sql="select * from datainfo where time between '"+start+"' and '"+end+"'";  取时间段内的数据
select * from datainfo where time between "2009-11-03 11:16:59"and "2009-11-03 11:18:59"

3.按某个字段降序排列并选取第一个
sql="select * from datainfo,nodeinfo where nodeinfo.nodeid="+Integer.parseInt(param)+" and nodeinfo.nodeip=datainfo.ip
order by time desc limit 0,1"; 按时间降序排列 只取第一个
(limit 0,1 是只取记录中的第一条.所以这条语句只能得到一条记录
  如想取前10条则 limit 0,10或limit 10
  如想取第10至20条则 limit 10,20 )

4.出现Operation not allowed after ResultSet closed的错误
    一个stmt多个rs进行操作.那么从stmt得到的rs1,必须马上操作此rs1后,才能去得到另外的rs2,再对rs2操作.不能互相交替使用,会引起rs已经关闭错误.    错误的代码如下:
       stmt=conn.createStatement();
       rs=stmt.executeQuery("select * from t1");
       rst=stmt.executeQuery("select * from t2"); rs.last();
       //由于执行了rst=stmt.executeQuery(sql_a);rs就会被关闭掉!所以程序执行到此会提示ResultSet已经关闭.
    错误信息为:java.sql.SQLException: Operation not allowed after ResultSet closed rst.last();
    正确的代码:
       stmt=conn.createStatement();
       rs=stmt.executeQuery("select * from t1");
       rs.last();//对rs的操作应马上操作,操作完后再从数据库得到rst,再对rst操作
       rst=stmt.executeQuery("select * from t2"); rst.last();原因是: The object used for executing a static SQL statement and returning the results it produces.     
      By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.    
       一个stmt最好对应一个rs, 如果用一个时间内用一个stmt打开两个rs同时操作,会出现这种情况.所以解决此类问题:1.就多创建几个stmt,一个stmt对应一个rs;2.若用一个stmt对应多个rs的话,那只能得到一个rs后就操作,处理完第一个rs后再处理其他的,如上"正确代码".多个stmt对应各自的rs.stmt=conn.createStatement();stmt2=conn.createStatement();rs=stmt.executeQuery("select * from t1");rst=stmt2.executeQuery("select * from t2");rs.last();rst.last();

原创粉丝点击