1、需要下载一个jar包。地址 http://pan.baidu.com/s/1i50LRId
2、代码如下:
import java.sql.*; public class Mytest { public static void main(String[] args){ String sql = "select * from student"; String url = "jdbc:sqlserver://WANGHONGHONG-PC\\SQLSERVER2;DatabaseName=hh"; String username = "sa"; String password = "sa@12345"; Connection conn; Statement stmt; ResultSet rs; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); System.out.println(rs.next()); rs.close(); stmt.close(); conn.close(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
3、效果:
4、又完善一版(添加输出)
import java.sql.*; public class Mytest { public static void main(String[] args){ String sql = "select * from student"; String url = "jdbc:sqlserver://WANGHONGHONG-PC\\SQLSERVER2;DatabaseName=hh"; String username = "sa"; String password = "sa@12345"; Connection conn; Statement stmt; ResultSet rs; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString("name")); } rs.close(); stmt.close(); conn.close(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
请各位大神们指点一二