一.JDBC操作数据库的步骤
1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library
2.加载数据库驱动
3.使用驱动管理器来获得连接---获得 一个数据库连接对象Connectiion
4.使用Connection创建PreparedStatement语句对象---PreparedStatement对象可以执行sql语句
5.使用PreparedStatement对象执行sql语句
6.操作判断---增删改返回的是影响行数,只有查询获得结果
@Test
public void testSelectAll() throws ClassNotFoundException, SQLException {
//1.加载数据库驱动
Class.forName(driver);
//2.使用驱动管理器来获得链接---获得一个数据库连接对象Connection
Connection con = DriverManager.getConnection(url, username, password);
//3.使用Connection创建PreparedStatement预处理对象---PreparedStatement对象可以
//执行带 ? 的sql语句
String sql="select * from student";
PreparedStatement ps = con.prepareStatement(sql);
//4.使用PreparedStatement对象执行SQL语句,获得ResultSet结果集对象
ResultSet rs = ps.executeQuery();
//5.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值
//ResultSet)
List<Student> studentList=new ArrayList<>();
while(rs.next()){
//更具字段名城获取表中的数据
int stuId=rs.getInt("stuId");
String stuName = rs.getString("stuName");
String stuSex = rs.getString("stuSex");
int stuAge = rs.getInt("stuAge");
String stuAddr = rs.getString("stuAddr");
//把以上数据封装到Student对象中
Student student=new Student();
student.setStuId(stuId);
student.setStuName(stuName);
student.setStuSex(stuSex);
student.setStuAge(stuAge);
student.setStuAddr(stuAddr);
//把当前行封装后的student 对象装在到list集合中
studentList.add(student);
}
System.out.println("studentList");
//6.关闭资源
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(con!=null){
con.close();
}
}
7.回收资源
二.什么是JDBC
概念:Java数据库连接,(Java Database Connectivity,简称JDBC)是ava语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的jDBC是面向关系型数据库的。
各数据库厂商根据IDBC的规范,实现自身数据库操作的功能代码,然后以jar包(数据库厂商提供的驱动包)的形式提供给开发人员使用,开发人员使用反射的机制创建这些具体实现类的兑现完成数据库的操作。