求大神看一下java连接sqlserver2005问题

益达先生 发布于 2013/09/09 15:45
阅读 157
收藏 0

为什么得到的count始终是1?可是我把sql语句在数据库查询有10条,代码如下:

public class TestRes {

	public static Connection conn;

	public static Connection getConn() {
		String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test";
		String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String user = "sa";
		String password = "111111";
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url, user, password);
			System.out.println("数据库连接成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("数据库连接失败");
			e.printStackTrace();
		}
		return conn;
	}
	public int  swtSL(){
		int count=0;
		try {
		ResultSet rs = getConn().prepareStatement("select top 10 id from Track").executeQuery();
		if(rs.next()){
			count=count+1;
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	     try {
	    	System.out.println(new TestRes().swtSL());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

真心搞不懂,请大婶帮忙看一下

 

 

 

 

 

 

加载中
0
easymbol
easymbol
if(rs.next()){
  count=count+1;

}

益达先生
益达先生
好吧,迷糊了,刚刚检查出来了,谢谢了。
实迷途其未远觉今是而昨非
实迷途其未远觉今是而昨非
+1,if只执行一次,应该用while,一直到不符合条件的时候结束循环
0
我已经报警了
我已经报警了
打印一下看看
public class TestRes {

	public static Connection conn;

	public static Connection getConn() {
		String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test";
		String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String user = "sa";
		String password = "111111";
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url, user, password);
			System.out.println("数据库连接成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("数据库连接失败");
			e.printStackTrace();
		}
		return conn;
	}
	public int  swtSL(){
		int count=0;
		try {
		ResultSet rs = getConn().prepareStatement("select top 10 id from Track").executeQuery();
		if(rs.next()){
syso(rs.getInt("id"));
			count=count+1;
syso(count);
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	     try {
	    	System.out.println(new TestRes().swtSL());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
0
QAllen
QAllen
if条件语句不会循环。
益达先生
益达先生
嗯,谢谢了
返回顶部
顶部