search
HomeDatabaseMysql Tutorial数据库访问技术之JDBC

数据库访问技术之JDBC

Jun 07, 2016 pm 03:57 PM
jdbclearnCanustechnologydatabaseaccess

在了解JDBC之前呢,我们可以先对ODBC做一个回顾,以便于更好的理解JDBC。看名字也知道这两个关系不一般,他们实现了同样的功能,为应用程序连接和操作数据库提供支持。所以,我们先从ODBC开始。 ODBC ODBC(Open Database Connectivity)是开放数据库互连的简称

在了解JDBC之前呢,我们可以先对ODBC做一个回顾,以便于更好的理解JDBC。看名字也知道这两个关系不一般,他们实现了同样的功能,为应用程序连接和操作数据库提供支持。所以,我们先从ODBC开始。

ODBC

ODBC(Open Database Connectivity)是开放数据库互连的简称,是一种使用SQL的应用程序接口。它是一系列的规范和对数据库访问的API。那么API+SQL就可以执行对数据库的操作。它是不依赖于DBMS的,即通过ODBC可以以相同的方式连接大部分数据库。它包括了应用程序接口、驱动器管理器、数据库驱动器、数据源。下面我们通过一副图来了解ODBC各个部分之间的关系:

\

JDBC

之前说过了JDBC和ODBC实际上的功能是一致的,只不过实现不太一样。首先ODBC是基于C++语言的,那么与Java的面向对象思想不太相符,通信比较困难。因此,JDBC就出项了,即JDBC是基于JAVA语言的数据库访问API接口。然后其他内容就和ODBC基本一致了。只要你了解了ODBC,那么在概念上基本就理解了JDBC。那么你需要做的就是对新面孔出项的接口再了解一遍就好了,并且这些接口的功能和ODBC是一致的,只是说在实现上有细微的差别。下面也看看JDBC的结构图:
\

连接方式

由上面的结构图可以看出来,JDBC提供了多种不同的连接方式。这个做个大概的了解吧,因为这主要是数据库厂商关心的事,我们知道就好了,有些也确实不是很明白。
1、JDBC-ODBC连接桥:这种方式是一位ODBC为基础的,上面说了java应用程序和ODBC之间的通信是有点麻烦的。但是ODBC作为一种数据库访问的标准应用是很广的。因此JDBC通过映射ODBC的功能调用就保证了原来使用ODBC的数据库也可以很方便的访问的。
2、本地API驱动:即把JDBC调用转换为对数据库接口的客户端二进制代码库的调用。但是这个接口库依赖于产商,因为这里我们调用的不是数据库厂商提供的JDBC的接口实现。
3、纯Java本地协议:即把JDBC调用映射为DBMS的网络监听协议的功能调用,监听程序监听到请求后执行相关的数据库操作。监听程序是由厂商提供的。

常用接口简介

  DriverManager

关于驱动程序如何注册的,我们不需要知道。我们需要知道的是,如何调用方法去加载得到数据库驱动程序就好了。即Class.forName()方法,调用这个方法需要传递一个包含该驱动程序类名的String对象作为实参。如下:
    Class.forName("oracle.jdbc.driver.OracleDriver")

Connection

加载了驱动程序后,与数据库建立连接需要调用DriverManager.getConnection()方法,此方法需要数据库URL作为参数,不同的数据库URL的有些区别,但都符合“协议名 + Ip地址+端口号+数据库名”的格式。数据库用户名和密码如果有,也得加上,如下:
        String url = "jdbc:oracle:thin:@localhost:1521:pdborcl";
	String username = "123";
	String password = "123";
        Connection conn = DriverManager.getConnection(url, username, password);

StateMent

执行静态的SQL语句,它还可以组合多个SQL语句成为一个批处理,整体提交给数据库。我们通过Connection对象来创建Statement对象,然后用Statement的execute方法来执行SQL。另外PreparedStatement对象是继承自Statement对象的,这里我们用PreparedStatement为例,需要注意的是批处理只能用Statement对象来执行。
      PreparedStatement  pstmt = conn.prepareStatement("select * from t_user where userId=?");
      pstmt.setInt(1, id);
      ResultSet rs = pstmt.executeQuery();

ResultSet

执行一个SQL查询之后的结果集,Result具有指向当前行的指针,可以用来读取结果集中的数据。初始时指针指向第一行前面。该对象的Next()方法可以移动指针。如果Next()之后的行合法返回True,否则False。因此,循环时Next()方法作为判断依据。
到这里JDBC的简单介绍就结束了,JDBC在使用中充当了一个沟通者的角色。这让我想起姚明在NBA打球的那个设计模式:适配器模式,这也就成就了Java应用程序跨平台的特性。同时,JDBC、ODBC等也是面向接口编程思想的典型体现。 对了,这里还缺了一个OLE DB,没有提及。下回吧……
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software