博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jdbc的使用
阅读量:3951 次
发布时间:2019-05-24

本文共 2284 字,大约阅读时间需要 7 分钟。

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("关闭成功"); } }}

转载地址:http://yhrwi.baihongyu.com/

你可能感兴趣的文章
Linux学习之网络IO,磁盘io
查看>>
ES7.6.2安装
查看>>
查看jar依赖树
查看>>
idea运行gradle项目
查看>>
es安装ltr插件
查看>>
es插件使用之ltr插件demo体验
查看>>
开源ltr-es-7.6.2代码到本地idea打开出现各种错误总结
查看>>
Requests实践详解&& python通过连接开启https的elasticsearch7 服务器
查看>>
ES查询流程源码解析
查看>>
ldaps与ldap over TLS
查看>>
jvm为什么把-Xms和-Xmx的值设置成一样
查看>>
GC打印日志分析
查看>>
jvm堆模型
查看>>
jvm堆内存分带gc算法对比
查看>>
字符串常量池分布位置
查看>>
arm操作系统安装ldap问题
查看>>
java.lang.OutOfMemoryError:Direct buffer memory 分析
查看>>
如何设置常用JVM参数设置
查看>>
oom分析过程
查看>>
oom堆转储jvm参数设置
查看>>