JDBC访问数据库的步骤:
1、加载数据库驱动
2、获取数据库链接
3、构造SQL
4、执行SQL获取结果集
5、对结果集进行操作
- //1、加载驱动
- Class.forName("com.mysql.jdbc.Driver");
-
- //2、获取数据库连接
- Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/study", "root", "root");
-
- //3、构造SQL
- String sql = "select * form student where sid = ?";
- PreparedStatement ps = conn.prepareStatement(sql);
- ps.setInt(0, 1);
-
- //4、执行sql,获取结果集
- ResultSet resultSet = ps.executeQuery();
-
- //5、对结果集进行操作
- int id = resultSet.getInt(0);
- String name = resultSet.getString(1);
- int age = resultSet.getInt(2);
-
- System.out.println("id = " + id + "\tname = " + name + "\t age = " + age);
复制代码 |