Jdbc 连接数据库
Jdbc连接数据库步骤
1. 通过反射加载驱动
2. 获取连接 得到connection
3. 写sql语句
4. 获取执行sql对象(statment preparestament)增删改通过连接conn对象获得sql对象preparestament
5. 替换占位符
6. (拿到结果集) 返回影响的行数int rs=ps.executeUpdate()或resultSet rs=ps.executeQuery()
7. 关系数据库资源
代码如下
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1、通过反射加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2、通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
//3、定义sql语句 ?表示占位符
String sql = "select * from user where username = ?";
//4、获取预处理statement
preparedStatement = connection.prepareStatement(sql);
//5、设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "王五");
//6、向数据库发出sql执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();
//7、遍历查询结果集
while(resultSet.next()){
User user
System.out.println(resultSet.getString("id")+" "+resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//8、释放资源
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
statement PreparedStatement 区别
连接得到 statement PreparedStatement 首先父子关系 有缺点 statement 不安全 效率低,拼接麻烦,
PreparedStatement 优点 安全 效率高 预编译 缺点: 每一个都要一一对应
// 查询
/通过连接获取 PreparedStatement =conn.prepareStatement(传的是你的sql语句)
//替换占位符 ps.setObject(“索引(从一开始)”,”拼接具体数据”);