try {
if(resultSet!=null){
resultSet.close();
}
}catch (SQLException e){
e.printStackTrace();
}finally {
try {
if(preparedStatement!=null){
preparedStatement.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}

转载:https://www.cnblogs.com/erbing/p/5805727.html

一、相关概念

1.什么是JDBC

  JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

2.数据库驱动

  我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。其实也就是数据库厂商的JDBC接口实现,即对Connection等接口的实现类的jar文件。

二、常用接口

1.Driver接口

  Driver接口由数据库厂家提供,作为java开发人员,只需要使用Driver接口就可以了。在编程中要连接数据库,必须先装载特定厂商的数据库驱动程序,不同的数据库有不同的装载方法。如:

  装载MySql驱动:Class.forName("com.mysql.jdbc.Driver");

  装载Oracle驱动:Class.forName("oracle.jdbc.driver.OracleDriver");

2.Connection接口

  Connection与特定数据库的连接(会话),在连接上下文中执行sql语句并返回结果。DriverManager.getConnection(url, user, password)方法建立在JDBC URL中定义的数据库Connection连接上。

  连接MySql数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");

  连接Oracle数据库:Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");

  连接SqlServer数据库:Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");

  常用方法:

    • createStatement():创建向数据库发送sql的statement对象。
    • prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
    • prepareCall(sql):创建执行存储过程的callableStatement对象。
    • setAutoCommit(boolean autoCommit):设置事务是否自动提交。
    • commit() :在链接上提交事务。
    • rollback() :在此链接上回滚事务。

3.Statement接口

  用于执行静态SQL语句并返回它所生成结果的对象。

  三种Statement类:

    • Statement:由createStatement创建,用于发送简单的SQL语句(不带参数)。
    • PreparedStatement :继承自Statement接口,由preparedStatement创建,用于发送含有一个或多个参数的SQL语句。PreparedStatement对象比Statement对象的效率更高,并且可以防止SQL注入,所以我们一般都使用PreparedStatement。
    • CallableStatement:继承自PreparedStatement接口,由方法prepareCall创建,用于调用存储过程。

  常用Statement方法:

    • execute(String sql):运行语句,返回是否有结果集
    • executeQuery(String sql):运行select语句,返回ResultSet结果集。
    • executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。
    • addBatch(String sql) :把多条sql语句放到一个批处理中。
    • executeBatch():向数据库发送一批sql语句执行。

4.ResultSet接口

  ResultSet提供检索不同类型字段的方法,常用的有:

    • getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
    • getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
    • getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
    • getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
    • getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。

  ResultSet还提供了对结果集进行滚动的方法:

    • next():移动到下一行
    • Previous():移动到前一行
    • absolute(int row):移动到指定行
    • beforeFirst():移动resultSet的最前面。
    • afterLast() :移动到resultSet的最后面。

使用后依次关闭对象及连接:ResultSet → Statement → Connection

三、使用JDBC的步骤

  加载JDBC驱动程序 → 建立数据库连接Connection → 创建执行SQL的语句Statement → 处理执行结果ResultSet → 释放资源

1.注册驱动 (只做一次)

  方式一:Class.forName(“com.MySQL.jdbc.Driver”);
  推荐这种方式,不会对具体的驱动类产生依赖。
  方式二:DriverManager.registerDriver(com.mysql.jdbc.Driver);
  会造成DriverManager中产生两个一样的驱动,并会对具体的驱动类产生依赖。

2.建立连接

 Connection conn = DriverManager.getConnection(url, user, password); 

  URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:

其他参数如:useUnicode=true&characterEncoding=utf8

3.创建执行SQL语句的statement

//存在sql注入风险,statement

public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
testDelete(); } public static void testDelete() throws SQLException{
Connection connection=getConnection();
Statement statement=createStatement(connection);
String id="2";
//存在sql注入的危险
//如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录
String sql="delete from t_blog where id="+id;
statement.execute(sql);
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcUrl,user,pwd);
} public static Statement createStatement(Connection connection) throws SQLException {
return connection.createStatement();
}

//不存在sql诸如风险,PreparedStatement

public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
testPreparedStatement();
} public static void testPreparedStatement() throws SQLException {
Connection connection = getConnection();
int id = 1;
String sql = "delete from t_blog where id=?";
//PreparedStatement 有效的防止sql注入(SQL语句在程序运行前已经进行了预编译,当运行时动态地把参数传给PreprareStatement时,
//即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令)
PreparedStatement preparedStatement = createPreparedStatement(connection, sql);
preparedStatement.setInt(1, id);//占位符顺序从1开始
int clomSize = preparedStatement.executeUpdate();
System.out.println("影响的数据库行数=》" + clomSize); } public static PreparedStatement createPreparedStatement(Connection connection, String sql) throws SQLException {
return connection.prepareStatement(sql);
} public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcUrl, user, pwd);
}

//处理结果

public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
testResult();
} public static void testResult() throws SQLException{
Connection connection = getConnection();
int id=2;
String sql="select * from t_blog where id>=?";
PreparedStatement preparedStatement=createPreparedStatement(connection,sql);
preparedStatement.setInt(1,id);
ResultSet resultSet=preparedStatement.executeQuery();
while (resultSet.next()){
int rid=resultSet.getInt(1);
String name=resultSet.getString(2);
String context=resultSet.getString(3);
Date date=resultSet.getDate(4);
System.out.println("读取的记录=>"+rid+"-"+name+"-"+context+"-"+ DateFormatUtils.format(date,"yyyy-MM-dd HH:mm:ss"));
}
} public static PreparedStatement createPreparedStatement(Connection connection, String sql) throws SQLException {
return connection.prepareStatement(sql);
} public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcUrl, user, pwd);
}

//释放资源

try {
if(resultSet!=null){
resultSet.close();
}
}catch (SQLException e){
e.printStackTrace();
}finally {
try {
if(preparedStatement!=null){
preparedStatement.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}

四、事务(ACID特点、隔离级别、提交commit、回滚rollback

1.批处理Batch

public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
testBatch();
} public static void testBatch() throws SQLException {
Connection connection = getConnection();
Statement statement=connection.createStatement();
for(int i=4;i<104;i++){
String sql="insert into t_blog (id,name,context,createDateTime) values ('"+i+"','tst3数据库','jdbc学习3','2018-01-01 12:00:00') ";
statement.addBatch(sql);
}
statement.executeBatch();
statement.close();
connection.close(); }

【数据库】jdbc详解的更多相关文章

  1. SAE上传web应用(包括使用数据库)教程详解及问题解惑

    转自:http://blog.csdn.net/baiyuliang2013/article/details/24725995 SAE上传web应用(包括使用数据库)教程详解及问题解惑: 最近由于工作 ...

  2. Spring4 JDBC详解

    Spring4 JDBC详解 在之前的Spring4 IOC详解 的文章中,并没有介绍使用外部属性的知识点.现在利用配置c3p0连接池的契机来一起学习.本章内容主要有两个部分:配置c3p0(重点)和 ...

  3. JDBC详解系列(二)之加载驱动

    ---[来自我的CSDN博客](http://blog.csdn.net/weixin_37139197/article/details/78838091)---   在JDBC详解系列(一)之流程中 ...

  4. JDBC详解系列(三)之建立连接(DriverManager.getConnection)

      在JDBC详解系列(一)之流程中,我将数据库的连接分解成了六个步骤. JDBC流程: 第一步:加载Driver类,注册数据库驱动: 第二步:通过DriverManager,使用url,用户名和密码 ...

  5. JDBC详解(一)

    一.相关概念介绍 1.1.数据库驱动 这里驱动的概念和平时听到的那种驱动的概念是一样的,比如平时购买的声卡,网卡直接插到计算机上面是不能用的,必须要安装相应的驱动程序之后才能够使用声卡和网卡,同样道理 ...

  6. Java基础-面向接口编程-JDBC详解

    Java基础-面向接口编程-JDBC详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.JDBC概念和数据库驱动程序 JDBC(Java Data Base Connectiv ...

  7. JDBC详解1

    JDBC详解1 JDBC整体思维导图 JDBC入门 导jar包:驱动! 加载驱动类:Class.forName("类名"); 给出url.username.password,其中u ...

  8. windows phone 8.1开发SQlite数据库操作详解

    原文出自:http://www.bcmeng.com/windows-phone-sqlite1/ 本文小梦将和大家分享WP8.1中SQlite数据库的基本操作:(最后有整个示例的源码)(希望能通过本 ...

  9. MySQL数据库优化详解(收藏)

    MySQL数据库优化详解 mysql表复制 复制表结构+复制表数据mysql> create table t3 like t1;mysql> insert into t3 select * ...

  10. 如何查看mysql数据库的引擎/MySQL数据库引擎详解

    一般情况下,mysql会默认提供多种存储引擎,你可以通过下面的查看: 看你的mysql现在已提供什么存储引擎:mysql> show engines; 看你的mysql当前默认的存储引擎:mys ...

随机推荐

  1. 继承,C++

    body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...

  2. pymongo 对mongoDB的操作

    #文档地址 http://api.mongodb.com/python/current/api/pymongo/collection.html collection级别的操作: find_and _m ...

  3. 无法卸载Sql Server 的解决办法

    提示如下: 解决办法: 命令提示符——>wmic——>product list 找到与Sql Server 有关的程序: 重新打开一个命令提示符: 执行卸载命令:msiexec /x {7 ...

  4. DevExpress WinForms v18.2新版亮点(一)

    行业领先的.NET界面控件2018年第二次重大更新——DevExpress v18.2日前正式发布,本站将以连载的形式为大家介绍各版本新增内容.本文将介绍了DevExpress WinForms v1 ...

  5. 卷积神经网络-Dropout

    dropout 是神经网络用来防止过拟合的一种方法,很简单,但是很实用. 基本思想是以一定概率放弃被激活的神经元,使得模型更健壮,相当于放弃一些特征,这使得模型不过分依赖于某些特征,即使这些特征是真实 ...

  6. vue-router + ElementUI实现NavMenu 导航菜单 选中状态的切换

    elemen-ui官方网站:http://element.eleme.io/#/zh-CN/component/menu 新手小白利用vue+element-ui尝试搭建后台管理系统, 效果是这样的, ...

  7. linux执行可执行文件时报xxx:not found

    实际上是因为可执行文件执行时所依赖的动态链接库找不到,解决方法为在编译时加-static表示使用静态链接. 或者使用arm-linux-readelf -d +可执行文件,查看该可执行文件依赖的动态链 ...

  8. 团队-团队编程项目爬取豆瓣电影top250-代码设计规范

    1.类名使用首字母大写(骆驼命名法) 2.函数名应该为小写 3.用下划线开头定义私有的属性或方法 4.命名要使用有意义的,英文单词或词组 5.行尾不加分号 6.4个空格缩进代码 7.操作运算符注意优先 ...

  9. spark:ML和MLlib的区别

    ML和MLlib的区别如下: ML是升级版的MLlib,最新的Spark版本优先支持ML. ML支持DataFrame数据结构和Pipelines,而MLlib仅支持RDD数据结构. ML明确区分了分 ...

  10. GB2312汉字编码字符集对照表

    第01区 +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F A1A0 . . ・ ˉ ˇ ¨ " 々 ― - | - ' ' A1B0 &quo ...