JDBC:Java DataBase Connection Java数据库连接,用来操作关系型数据库。
连接数据库步奏:
1.加载驱动:
Class.forName("com.mysql.jdbc.Driver");
2.获取连接
Connection connection = DriverManager.getConnection("url", "账号", "密码");
url:jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8
账号,密码是在数据库找,一般都是root
3.获取到Statement对象,用来执行静态sql语句
Statement statement = connection.createStatement();
4.执行静态sql,获取结果集
ResultSet rSet = statement.executeQuery("select * from person");
5.遍历结果集,获取数据
while (rSet.next()) {
int id = rSet.getInt("id");
String name = rSet.getString("name");
String pass = rSet.getString("pass");
int age = rSet.getInt("age");
System.out.println(id+" "+name+" "+pass+" "+age);
}
6.关闭数据库连接,要按创建的倒序关闭
rSet.close();
statement.close();
connection.close();
当我们要执行动态sql的时候,即添加限定条件,第3,4步要换成下面代码,使用预处理:PreparedStatement接口来执行动态sql
PreparedStatement pstatement = connection.
prepareStatement("select * from person where id=?");
pstatement .serInt(1,2)//将sql中第1个问号换成2
网友评论