概念:
JDBC全称是Java DataBase Connectivity。
JDBC是java提供的一套接口规范,具体的驱动由数据库厂商实现。
基本步骤
1:注册驱动
1
| Class.forName("com.mysql.jdbc.Driver");
|
2:连接数据库
1 2
| Connection con = DriverManager.getConnection("jdbc:mysql:///exam", "root", "root");
|
3:编写SQL语句
1
| String sql = "SELECT * FROM dept;";
|
4:执行SQL
4-1:statement对象
1 2 3 4 5 6
| Statement statement = con.createStatement();
int row = statement.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(sql);
|
4-2:PreparedStatement对象
1 2 3 4 5 6 7
| PreparedStatement stmt = connection.prepareStatement(loginSql);
stmt.setString(1,userName);
ResultSet rs=stmt.executeQuery();
|
5:结果集迭代
1 2 3 4 5 6 7 8
| while(rs.next()){ int deptno = rs.getInt("deptno"); String dname = rs.getString(2); String loc = rs.getString("loc"); System.out.println(deptno+"\t\t\t"+dname+"\t\t\t"+loc); }
|
6:释放资源
1 2 3 4
| rs.close(); stmt.close(); conn.close();
|