jdbc的使用
jdbc因为每次都需要去执行创建连接等操作,所以已经不常用了,现在的各个框架都使用配置文件来简化开发了,例如springboot整合的mybatis,springboot-jpa
不过还是可以了解一下
如果没有使用maven就得自己去添加jar包
如果使用了maven就在pom.xml文件中添加依赖,依赖可以百度
jdbc 的使用分为7步
(1)加载驱动
(2)创建连接
(3)编写sql语句
(4)得到preparedstatement对象
(5)执行操作得到sql语句
(6)处理resultset结果集
(7)关闭连接3个都要关闭
package example.dao;
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
try {
//1,加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建连接
//此处按照实际的数据库名称和账号密码进行修改
//格式为jdbc:mysql://127.0.0.1:3306/数据库名称?useSSL=true&characterEncoding=utf-8&user=账号名&password=密码
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=true&characterEncoding=utf-8&user=root&password=root");
System.out.println("创建连接成功");
//3.写sql
//根据数据库实际的表名写SQL语句
String sql="select * from emp";
//4.得到statement对象执行sql
statement = connection.prepareStatement(sql);
//5.得到结果集
rs = statement.executeQuery();
//6.处理结果集
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//7.关闭
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("关闭成功");
}
}
}