Home Java javaTutorial Detailed explanation of what is JDBC? How is JDBC used?

Detailed explanation of what is JDBC? How is JDBC used?

Oct 19, 2018 pm 04:59 PM
java jdbc database

This article brings you a detailed explanation of what is JDBC? How is JDBC used? . It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is JDBC

JDBC (Java Database Connectivity), that is, Java database connection, is a Java API used to execute SQL statements , which can provide the same access to multiple relational databases. It consists of a set of classes and interfaces written in Java language. JDBC provides a baseline against which more advanced tools and interfaces can be built, enabling database developers to write database applications. All in all, JDBC does three things:

  1. Establish a connection to the database

  2. Send statements to operate the database

  3. Processing Result

JDBC Simple Example

The following code demonstrates how to exploit JDBC queries several pieces of data that meet the requirements from the database, and the database used is MySql.

1. Create a database and a table. My habit is to create a .sql file under CLASSPATH to store sql statements

create database school;

use school;

create table student
(
    studentId            int                 primary key    auto_increment    not null,
    studentName        varchar(10)                                                            not null,
    studentAge        int,
    studentPhone    varchar(15)
)

insert into student values(null,'Betty', '20', '00000000');
insert into student values(null,'Jerry', '18', '11111111');
insert into student values(null,'Betty', '21', '22222222');
insert into student values(null,'Steve', '27', '33333333');
insert into student values(null,'James', '22', '44444444');
commit;
Copy after login

2. Create a .properties file for Stores several properties of the MySql connection. Why create .properties instead of hard-coding it in the code? Since this is not a classification of Java design patterns, I won’t go into details. Just remember: From a design perspective, write the content in the configuration It's always better to have it in a file than hard-coded in code.

mysqlpackage=com.mysql.jdbc.Driver
mysqlurl=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8
mysqlname=root
mysqlpassword=root
Copy after login

3. Create entity classes based on table fields

public class Student
{
    private int        studentId;
    private String    studentName;
    private int        studentAge;
    private String    studentPhone;
    
    public Student(int studentId, String studentName, int studentAge,
            String studentPhone)
    {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentAge = studentAge;
        this.studentPhone = studentPhone;
    }
    
    public int getStudentId()
    {
        return studentId;
    }

    public String getStudentName()
    {
        return studentName;
    }

    public int getStudentAge()
    {
        return studentAge;
    }

    public String getStudentPhone()
    {
        return studentPhone;
    }

    public String toString()
    {
        return "studentId = " + studentId + ", studentName = " + studentName + ", studentAge = " +
                studentAge + ", studentPhone = " + studentPhone;
    }
}
Copy after login

4. Write a DBConnection class specifically to provide external database connections. I use MySql here, so there is only one mysqlConnection. If Oracle is also used, of course, an oracleConnection can be provided externally. Some people may wonder whether there are thread safety issues in making these connections global. This is a good question. That's because we only read a PreparedStatement from the Connection and will not write it. Reading only without modification will not cause thread safety issues. In addition, setting the Connection to static ensures that there is only one copy of the Connection in the memory and will not occupy much resources. It will be fine if you do not call the close() method to close it after each use.

public class DBConnection
{    
    private static Properties properties = new Properties();
    
    static
    {
        /** 要从CLASSPATH下取.properties文件,因此要加"/" */
        InputStream is = DBConnection.class.getResourceAsStream("/db.properties");
        try
        {
            properties.load(is);
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /** 这个mysqlConnection只是为了用来从里面读一个PreparedStatement,不会往里面写数据,因此没有线程安全问题,可以作为一个全局变量 */
    public static Connection mysqlConnection = getConnection();
    
    public static Connection getConnection()
    {
        Connection con = null;
        try
        {
            Class.forName((String)properties.getProperty("mysqlpackage"));
            con = DriverManager.getConnection((String)properties.getProperty("mysqlurl"), 
                    (String)properties.getProperty("mysqlname"), 
                    (String)properties.getProperty("mysqlpassword"));
        } 
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        } 
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return con;
    }
}
Copy after login

5. Create a tool class to write various methods specifically to interact with the database. It is best to make this kind of tool class a singleton, so that you don’t have to create new every time (in fact, I don’t see any benefits of new), and save resources

package com.xrq.test11;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StudentManager
{
    private static StudentManager instance = new StudentManager();
    
    private StudentManager()
    {
        
    }
    
    public static StudentManager getInstance()
    {
        return instance;
    }
    
    public List<Student> querySomeStudents(String studentName) throws Exception
    {
        List<Student> studentList = new ArrayList<Student>();
        Connection connection = DBConnection.mysqlConnection;
        PreparedStatement ps = connection.prepareStatement("select * from student where studentName = ?");
        ps.setString(1, studentName);
        ResultSet rs = ps.executeQuery();
        
        Student student = null;
        while (rs.next())
        {
            student = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
            studentList.add(student);
        }
        
        ps.close();
        rs.close();
        return studentList;
    }
}
Copy after login

6. Write a main Call the function

List<Student> studentList = StudentManager.getInstance().querySomeStudents("Betty");
for (Student student : studentList) {
    System.out.println(student);
}
Copy after login

7. Look at the running results. They are the same as those in the database. Success

studentId = 1, studentName = Betty, studentAge = 20, studentPhone = 00000000
studentId = 3, studentName = Betty, studentAge = 21, studentPhone = 22222222
Copy after login

Why use placeholders "?"

Look at point 5. You must have noticed that the "?" placeholder is used when writing SQL statements. Of course, there are factors to beautify the code. If you don't use placeholders, you must put them in parentheses. Write " " to splice parameters. If there are too many parameters to be spliced, the code will definitely not look good and the readability will not be strong. But in addition to this reason, there is another important reason, which is to avoid a security issue. Assuming that we do not use placeholders to write SQL statements, then the "querySomeStudents(String name) throws Exception" method should be written like this:

public List<Student> querySomeStudents(String studentName) throws Exception
{
    List<Student> studentList = new ArrayList<Student>();
    Connection connection = DBConnection.mysqlConnection;
    PreparedStatement ps = connection.prepareStatement("select * from student where studentName = '" + studentName + "'");
    ResultSet rs = ps.executeQuery();
        
    Student student = null;
    while (rs.next())
    {
        student = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
        studentList.add(student);
    }
        
    ps.close();
    rs.close();
    return studentList;
}
Copy after login

The above main function can also obtain two pieces of data, but here comes the problem. What if I call it like this:

public static void main(String[] args) throws Exception
    {
        List<Student> studentList = new ArrayList<Student>();
        studentList = StudentManager.getInstance().querySomeStudents("' or '1' = '1");
        for (Student student : studentList)
            System.out.println(student);
    }
Copy after login

Look at the running results:

studentId = 1, studentName = Betty, studentAge = 20, studentPhone = 00000000
studentId = 2, studentName = Jerry, studentAge = 18, studentPhone = 11111111
studentId = 3, studentName = Betty, studentAge = 21, studentPhone = 22222222
studentId = 4, studentName = Steve, studentAge = 27, studentPhone = 33333333
studentId = 5, studentName = James, studentAge = 22, studentPhone = 44444444
Copy after login

Why? Just look at the sql statement after splicing and you will know:

select * from student where studentName = '' or '1' = '1'
Copy after login

'1'='1' is always true, so the previous query conditions are useless. This kind of problem has application scenarios and is not just written casually. Java is used more and more on the Web. Since it is the Web, when querying, there is a situation where the user enters a condition, the query condition is obtained in the background, and the SQL statement is spliced ​​to query the database. Experienced users can enter a "' '' or '1' = '1", so you can get all the data in the library.

The relationship and difference between Statement and PreparedStatement.

Relationship: PreparedStatement inheritance Since Statement, both interfaces
Difference: PreparedStatement can use placeholders, is precompiled, and batch processing is more efficient than Statement

JDBCTransaction

What is a transaction: A transaction is a set of operations for a set of database operations. If a set of processing steps either all occur or none are performed, we call the reorganization process a transaction.

Basic characteristics of transactions: atomicity, consistency, isolation, and durability.

Atomicity: Atomicity means that a transaction is an indivisible unit of work, and all operations in the transaction either occur or none occur.

Consistency: Consistency means that the integrity constraints of the database are not violated before the transaction starts and after the transaction ends. This means that database transactions cannot destroy the integrity of relational data and the consistency of business logic.

If A transfers money to B, regardless of whether the transfer transaction operation is successful or not, the total deposits of the two will remain unchanged.

Isolation: When multiple transactions access concurrently, the transactions are isolated, and one transaction should not affect the running effects of other transactions.

In a concurrent environment, when different transactions manipulate the same data at the same time, each transaction has its own complete data space . Modifications made by concurrent transactions must be isolated from modifications made by any other concurrent transactions. When a transaction views data updates, the state of the data is either the state before another transaction modified it, or the state after another transaction modified it. The transaction will not view the data in the intermediate state.

The most complex problems in transactions are caused by transaction isolation. Complete isolation is unrealistic. Complete isolation requires the database to only execute one transaction at a time, which will seriously affect performance.

Persistence: means that after the transaction is completed, the changes made by the transaction to the database will be persistently saved in the database and will not be recalled. roll.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit Java video tutorial, java development graphic tutorial, bootstrap video tutorial!

The above is the detailed content of Detailed explanation of what is JDBC? How is JDBC used?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

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.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles