什么是JDBC
java连接数据库的规范
JDBC核心思想
java定义了访问数据库的接口 可为多种关系型数据库提供统一的访问方式
JDBC开发步骤
1 导包 注册驱动
Class.forName(" com.mysql.jdbc.Driver ")
2 获取数据库连接对象
DriverManager.getConnection("jdbc:mysql://localhost :3306/数据库名","username","password")
3 准备sql语句
String sql="";
4 获取执行对象
Statement
5执行sql
如果是DQL语句用executequery
如果是DML语句用executeupdate
6 处理结果
如果是查询 返回修改的Resultset结果集
如果是增删改 返回的是修改的行数
7释放资源
也可以封装成工具类 方便调用
先编写配置文件
在src目录下 创建 resource 文件
eg
driverclassname=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/my2203?useSSL=false username=root password=1234
在工具类中 创建 properties集合读取配置文件 到prop集合
eg:
InputStream inputStream = conjdbc.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties prop= new Properties();
prop.load(inputStream);
根据键获取值
driverclassname =prop.getProperty("driverclassname");
url= prop.getProperty("url");
username= prop.getProperty("username");
password=prop.getProperty("password");
第一步先注册驱动
Class.forName(driverclassname);
上面这些都在静态代码块内执行
第二步创建一个返回值为连接对象的方法
eg
public static Connection getconnection( ) throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); return connection; }
第三步创建一个释放资源的方法
eg:
public static void close(Statement stat,Connection conn){ close(null,stat,conn); } public static void close(ResultSet rs, Statement sta,Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(sta!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } }