import java.sql.*;
public class Demo {
public static void main(String[] args) {
//声明变量
Connection con = null;
Statement sta = null;
ResultSet res = null;
try {
//数据库地址
String url = "jdbc:sqlserver://localhost:1433;databaseName=数据库名;";
//用户名,密码
String user = "sa";
String password = "1234";
//装载Class
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//连接数据库
con = DriverManager.getConnection(url, user, password);
sta = con.createStatement();
//执行SQL语句
String sql = "SELECT * FROM Table";
res = sta.executeQuery(sql);
//
while(res.next()){
System.out.println(res.getString("Name")+" "+res.getInt("Age")+" "+res.getString("Sex"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭数据库连接
if(res != null){
res.close();
}
if(sta != null){
sta.close();
}
if(con != null){
con.close();
}
}
}
}
使用sqljdbc4.jar