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

为什么得到的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();
		}
	}
}

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

 

 

 

 

 

 

举报
益达先生
发帖于5年前 3回/138阅
共有3个答案 最后回答: 5年前
打印一下看看
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();
		}
	}
}
顶部