Introduction

What's JDBC

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

JDBC library (includes APIs)的主要用途包括

  • Making a connection to a database. 连接数据库

  • Creating SQL or MySQL statements. 创建SQL或者MySQL语句

  • Executing SQL or MySQL queries in the database. 执行SQL或者MySQL查询

  • Viewing & Modifying the resulting records. 查看或者修改结果

JDBC架构

JDBC支持两层或者三层处理逻辑。但是一般,包括两层结构

  • JDBC API: This provides the application-to-JDBC Manager connection.

  • JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

JDBC drivers实现了JDBC APIs定义的接口。

JDBC连接

连接JDBC通常有四个简单的步骤

  • Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.

  • Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.

  • Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.

  • Create Connection Object: Finally, code a call to the DriverManagerobject's getConnection( ) method to establish actual database connection.

注册JDBC driver

注册JDBC driver有两种方法:

Approach 1: Class.forName() 自动将driver相关class加载到内存

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Approach 2: DriverManager.registerDriver() 如果使用的是 non-JDK compliant JVM

try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL formulation

加载完driver之后,可以用DriverManager.getConnection()建立连接。

下面是常用数据库与connection URL的映射表

RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName

JDBC statement,PreparedStatement & CallableStatement

根据不同的需用,可以选择不同的statement接口。

Interfaces Recommended Use
Statement Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters.

Statement

创建statement

Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}

执行statement

创建完statement object之后,可以用来执行SQL语句

  • boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.

  • int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.

  • ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.

关闭statement

如果close connection节省数据库资源一样,close statement可以确保资源的合理回收。

Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
stmt.close();
}

JDBC 批处理

批处理(batch processing)允许一次执行多条SQL语句。由于JDBC drivers并没有要求实现这个功能,因此使用前先用 DatabaseMetaData.supportsBatchUpdates() 检测目标数据库是否支持批处理。

Statement对象的批处理

  • Create a Statement object using either createStatement() methods.

  • Set auto-commit to false using setAutoCommit().

  • Add as many as SQL statements you like into batch using addBatch()method on created statement object.

  • Execute all the SQL statements using executeBatch() method on created statement object.

  • Finally, commit all the changes using commit() method.

// Create statement object
Statement stmt = conn.createStatement(); // Set auto-commit to false
conn.setAutoCommit(false); // Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL); // Create an int[] to hold returned values
int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes
conn.commit();

PreparedStatement对象的批处理

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(?, ?, ?, ?)"; // Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL); //Set auto-commit to false
conn.setAutoCommit(false); // Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch(); // Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch(); //add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes
conn.commit();

References

http://www.tutorialspoint.com/jdbc/jdbc-where-clause.htm

http://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database

JDBC入门学习的更多相关文章

  1. mysql的jdbc入门学习小结

    转自:专注JavaWeb开发 http://www.javaweb1024.com/data/MySQL/2015/04/25/618.html 一.jdbc基本概念jdbc : Java Datab ...

  2. MyBatis入门学习教程-使用MyBatis对表执行CRUD操作

    上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...

  3. MyBatis入门学习(二)

    在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...

  4. Jdbc入门

    JDBC入门 l  导jar包:驱动! l  加载驱动类:Class.forName(“类名”); l  给出url.username.password,其中url背下来! l  使用DriverMa ...

  5. JDBC 接口学习

    说明:文章所有内容皆选自实验楼教程[JDBC 入门教程],想要学习更多JDBC,可以点击教程进行学习~ JDBC 简介 JDBC 的全称是 Java Database Connectivity,叫做 ...

  6. day17(JDBC入门&jdbcUtils工具介绍)

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

  7. Mybatis基础入门学习

    Mybatis基础入门学习 mybatis架构分析 搭建测试mybatis架构 )下载并导入mybatis3.2.7.jar(架构),mysql-connector-java-5.1.7-bin.ja ...

  8. JDBC的学习 3-1

    JDBC的学习 3-1 JDBC基本概念 快速入门 对JDBC中各个接口和类详解 JDBC : 概念 :Java DateBase Connectivity java数据库连接,Java语言操作数据库 ...

  9. vue入门学习(基础篇)

    vue入门学习总结: vue的一个组件包括三部分:template.style.script. vue的数据在data中定义使用. 数据渲染指令:v-text.v-html.{{}}. 隐藏未编译的标 ...

随机推荐

  1. 在WINDOWS下初步试用OMNET++ 4

    闲扯: 最近实习公司要做ZIGBEE,我是对这个兴趣不大,但工作还是要做的,目前帮着找找合适的仿真软件,什么NS-2啊,OPNET啊. 正文: 这个软件软件直接去官网下载就好了,免费开源. 安装也比较 ...

  2. WordPress + Nginx +PHP+MySQL

    Windows下配置Nginx+php环境 1)php的安装与配置. 直接解压下载好的php包,到D盘wnmp目录(D:\wnmp),这里把解压出来的文件夹重命名成php5.进入文件夹修改php.in ...

  3. [AR]ImageTarget(图像识别)

    ImageTarget 前言 ImageTarget 顾名思义,就是图像识别,本文记录下作者最近学习vuforia中的imageTarget笔记与心得. vuforia guide:https://l ...

  4. Webform:Application、ViewState对象的用法

    Application Application对象的作用范围是整个全局,也就是说对所有用户都有效.它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所以可以在不同页面中对它进行存取.它和S ...

  5. ngx_http_upstream_module模块.md

    ngx_http_upstream_module ngx_http_upstream_module模块用于定义可由proxy_pass,fastcgi_pass,uwsgi_pass,scgi_pas ...

  6. Jmeter学习笔记TWO

    使用非GUI模式运行Jmeter脚本并自动生成测试报告 命令:jmeter -n -t tougu.jmx -l result.jtl -e -o /tmp/ResultReport 这个命令是用于执 ...

  7. 初次认识 C# win32 api

    第一次接触win32api,刚开始的时候有点迷迷糊糊的. Windows API 就是windows应用程序接口. win api向上就是windows应用程序,向下就是windows操作系统核心. ...

  8. HTML5 之 FileReader(图片上传)

    1.FileReader接口的方法 FileReader接口有4个方法,其中3个用来读取文件,另一个用来中断读取.无论读取成功或失败,方法并不会返回读取结果,这一结果存储在result属性中. Fil ...

  9. Codeforces 刷水记录

    Codeforces-566F 题目大意:给出一个有序数列a,这个数列中每两个数,如果满足一个数能整除另一个数,则这两个数中间是有一条边的,现在有这样的图,求最大联通子图. 题解:并不需要把图搞出来, ...

  10. SLES 11 SP3防火墙设置

    防火墙简介 SLES 11 SP3 系统安装后,防火墙一般是启动的,它有两个服务:SuSEfirewall2_setup.SuSEfirewall2_init 关闭防火墙 # 方法一 rcSuSEfi ...