最近在远标学java,老师布置了个任务让我们自学jdbc实现数据库操作,求
发布网友
发布时间:2022-04-07 23:34
我来回答
共1个回答
热心网友
时间:2022-04-08 01:04
Connection con = null;
try {
//1.加载驱动
String className = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(className);
//2。获取数据数据库连接
String url = "jdbc:sqlserver://localhost:1433; DatabaseName=student";
con = DriverManager.getConnection(url, "sa", "123456");
//3.获取Statement对象
Statement state = con.createStatement();
String sql = "select * from stu";
ResultSet rs = state.executeQuery(sql);
System.out.println("学号\t姓名\t年龄\t成绩");
System.out.println("------------------------------");
//5.从ResultSet里面获取每条记录数据
while(rs.next()){
String no = rs.getString(1);
String name = rs.getString(2);
int age = rs.getInt(3);
int score = rs.getInt(4);
System.out.println(no + "\t" + name + "\t" + age + "\t" + score);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}