JDBC连接MySQL数据库及示例
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:
具体代码:

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.
