JDBC是Sun公司制定的一个可以用Java语言连接数据库的技术。 一、JDBC基础知识 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC为数据
JDBC是Sun公司制定的一个可以用Java语言连接数据库的技术。
一、JDBC基础知识
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC为数据库开发人员提供了一个标准的API,据此可以构建更高级的工具和接口,使数据库开发人员能够用纯 Java API 编写数据库应用程序,并且可跨平台运行,并且不受数据库供应商的限制。
1、跨平台运行:这是继承了Java语言的“一次编译,到处运行”的特点;
2、不受数据库供应商的限制:巧妙在于JDBC设有两种接口,一个是面向应用程序层,其作用是使得开发人员通过SQL调用数据库和处理结果,而不需要考虑数据库的提供商;另一个是驱动程序层,处理与具体驱动程序的交互,JDBC驱动程序可以利用JDBC API创建Java程序和数据源之间的桥梁。应用程序只需要编写一次,便可以移到各种驱动程序上运行。Sun提供了一个驱动管理器,数据库供应商——如MySQL、Oracle,提供的驱动程序满足驱动管理器的要求就可以被识别,就可以正常工作。所以JDBC不受数据库供应商的限制。
JDBC API可以作为连接Java应用程序与各种关系数据库的纽带,在带来方便的同时也有负面影响,以下是JDBC的优、缺点。优点如下:
- 操作便捷:JDBC使得开发人员不需要再使用复杂的驱动器调用命令和函数;
- 可移植性强:JDBC支持不同的关系数据库,所以可以使同一个应用程序支持多个数据库的访问,只要加载相应的驱动程序即可;
- 通用性好:JDBC-ODBC桥接驱动器将JDBC函数换成ODBC;
- 面向对象:可以将常用的JDBC数据库连接封装成一个类,在使用的时候直接调用即可。
缺点如下:
- 访问数据记录的速度受到一定程度的影响;
- 更改数据源困难:JDBC可支持多种数据库,各种数据库之间的操作必有不同,这就给更改数据源带来了很大的麻烦
二、JDBC连接数据库的流程及其原理
1、在开发环境中加载指定数据库的驱动程序。例如,接下来的实验中,使用的数据库是MySQL,所以需要去下载MySQL支持JDBC的驱动程序(最新的是:mysql-connector-java-5.1.18-bin.jar);而开发环境是MyEclipse,将下载得到的驱动程序加载进开发环境中(具体示例的时候会讲解如何加载)。
2、在Java程序中加载驱动程序。在Java程序中,可以通过 “Class.forName(“指定数据库的驱动程序”)” 方式来加载添加到开发环境中的驱动程序,例如加载MySQL的数据驱动程序的代码为: Class.forName(“com.mysql.jdbc.Driver”)
3、创建数据连接对象:通过DriverManager类创建数据库连接对象Connection。DriverManager类作用于Java程序和JDBC驱动程序之间,用于检查所加载的驱动程序是否可以建立连接,然后通过它的getConnection方法,根据数据库的URL、用户名和密码,创建一个JDBC Connection 对象。如:Connection connection = DriverManager.geiConnection(“连接数据库的URL", "用户名", "密码”)。其中,URL=协议名+IP地址(域名)+端口+数据库名称;用户名和密码是指登录数据库时所使用的用户名和密码。具体示例创建MySQL的数据库连接代码如下:
Connection connectMySQL = DriverManager.geiConnection(“jdbc:mysql://localhost:3306/myuser","root" ,"root" );
4、创建Statement对象:Statement 类的主要是用于执行静态 SQL 语句并返回它所生成结果的对象。通过Connection 对象的 createStatement()方法可以创建一个Statement对象。例如:Statement statament = connection.createStatement(); 具体示例创建Statement对象代码如下:
Statement statamentMySQL =connectMySQL.createStatement();
5、调用Statement对象的相关方法执行相对应的 SQL 语句:通过execuUpdate()方法用来数据的更新,包括插入和删除等操作,例如向staff表中插入一条数据的代码:
statement.excuteUpdate( "INSERT INTO staff(name, age, sex,address, depart, worklen,wage)" + " VALUES ('Tom1', 321, 'M', 'china','Personnel','3','3000' ) ") ;
通过调用Statement对象的executeQuery()方法进行数据的查询,而查询结果会得到 ResulSet对象,ResulSet表示执行查询数据库后返回的数据的集合,ResulSet对象具有可以指向当前数据行的指针。通过该对象的next()方法,使得指针指向下一行,然后将数据以列号或者字段名取出。如果当next()方法返回null,则表示下一行中没有数据存在。使用示例代码如下:
ResultSet resultSel = statement.executeQuery( "select * from staff" );
6、关闭数据库连接:使用完数据库或者不需要访问数据库时,通过Connection的close() 方法及时关闭数据连接。
三、JDBC应用示例实验
实验内容:使用phpMyAdmin在MySQL中创建数据库(myuser),并添加实验所需的数据(新建staff表,添加一些记录);编写Java程序,利用JDBC连接在MySQL中创建好的数据库(myuser),对staff表格进行插入、更新、删除和查询等操作。
实验环境及开发工具:Win7操作系统;jdk1.6.0_26;XAMPP1.7.7(MySQL 5.1, phpMyAdmin);MyEclipse 8.5
实验环境的搭建:可参考我的博客
- Java环境搭配:http://blog.csdn.net/cxwen78/article/details/6400798;
- windows系统XAMPP安装配置使用:http://blog.csdn.net/cxwen78/article/details/6847927
实验过程及步骤:
1、下载MySQL支持JDBC的驱动程序:如果已经有了,可跳过这一步。前往MySQL官网(http://www.mysql.com/products/connector/ )下载驱动程序,,MySQL针对不同的平台提供了不同的连接器,我们需要的是DBC Driver for MySQL (Connector/J),如下图所示,点击 Download 跟着网站的引导进行下载。打开下载得到的压缩包(mysql-connector-java-5.1.18.zip),将其中的Java包(mysql-connector-java-5.1.18-bin.jar),复制到MySQL目录下(仅是为了方便才放到这里),以备加载驱动程序时使用。
2、创建数据库:使用phpMyAdmin,登录MySQL,创建数据库myuser,并在其中插入一个名为staff的表格。并添加一些数据,操作步骤如图,登录进去MySQL数据库后:
1)创建数据库,名称为myuser,编码为utf8_general_ci(支持中文);
2)新建表格,名称为staff,表格有8个字段;
3)8个字段的设置,包括名称、类型、值的长度、初始值、编码等等(点击查看大图);
4)添加成功后,查看的staff表格情况:
5)往表格中插入一些实验所需数据,需要插入两条,一个是员工lucy的,还有lili的:
3、在MyEclips中创建项目并在项目中添加MySQL驱动程序:创建的项目类型可以是Java项目或者是Java Web项目都可以。这里创建的是Web项目,项目名称可以随便取,我命名为“JavaWebChp07”。创建成功后将步骤1里下载得到的MySQL驱动程序包(mysql-connector-java-5.1.18-bin.jar)添加到工程的Build path中,添加过程如图所示:
4、编写JDBC连接MySQL数据库的实例具体代码,JDBC_Test.java:
具体代码:

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

There are four main index types in MySQL: B-Tree index, hash index, full-text index and spatial index. 1.B-Tree index is suitable for range query, sorting and grouping, and is suitable for creation on the name column of the employees table. 2. Hash index is suitable for equivalent queries and is suitable for creation on the id column of the hash_table table of the MEMORY storage engine. 3. Full text index is used for text search, suitable for creation on the content column of the articles table. 4. Spatial index is used for geospatial query, suitable for creation on geom columns of locations table.

TocreateanindexinMySQL,usetheCREATEINDEXstatement.1)Forasinglecolumn,use"CREATEINDEXidx_lastnameONemployees(lastname);"2)Foracompositeindex,use"CREATEINDEXidx_nameONemployees(lastname,firstname);"3)Forauniqueindex,use"CREATEU

The main difference between MySQL and SQLite is the design concept and usage scenarios: 1. MySQL is suitable for large applications and enterprise-level solutions, supporting high performance and high concurrency; 2. SQLite is suitable for mobile applications and desktop software, lightweight and easy to embed.

Indexes in MySQL are an ordered structure of one or more columns in a database table, used to speed up data retrieval. 1) Indexes improve query speed by reducing the amount of scanned data. 2) B-Tree index uses a balanced tree structure, which is suitable for range query and sorting. 3) Use CREATEINDEX statements to create indexes, such as CREATEINDEXidx_customer_idONorders(customer_id). 4) Composite indexes can optimize multi-column queries, such as CREATEINDEXidx_customer_orderONorders(customer_id,order_date). 5) Use EXPLAIN to analyze query plans and avoid

Using transactions in MySQL ensures data consistency. 1) Start the transaction through STARTTRANSACTION, and then execute SQL operations and submit it with COMMIT or ROLLBACK. 2) Use SAVEPOINT to set a save point to allow partial rollback. 3) Performance optimization suggestions include shortening transaction time, avoiding large-scale queries and using isolation levels reasonably.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

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),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

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
