import java.sql.*;
public class JDBC {
public static void main(String[]args){
//1.加载驱动
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.print("驱动包连接失败!");
}
String url="jdbc:sqlserver://localhost:1433;DatabaseName=StuInfor";;
String user="sa";
String password="sa";
Connection con=null;
PreparedStatement psta=null;
String sql="select*from Student";
ResultSet rs=null;
//2.连接数据库
try {
con=DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败!");
}
//3.创建 PreparedStatement对象
try {
psta=con.prepareStatement(sql);
// 创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。
rs=psta.executeQuery();
//在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象
//4.处理结果集,并调出数据库中的信息打印在控制台上
while(rs.next())
{
System.out.print("\n"+rs.getString(1)+"\t ");
System.out.print(rs.getString(2)+" \t");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");
System.out.print(rs.getString(5)+" ");
System.out.print(rs.getString(6)+" ");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//5.释放资源
finally{
try {
if(rs!= null){
rs.close();
}
psta.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}