国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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;

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

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;
????}
}

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();
????????}
????}
????
????/**?這個(gè)mysqlConnection只是為了用來從里面讀一個(gè)PreparedStatement,不會(huì)往里面寫數(shù)據(jù),因此沒有線程安全問題,可以作為一個(gè)全局變量?*/
????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;
????}
}

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;
????}
}

6. Write a main Call the function

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

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

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;
}

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);
????}

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

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

select?*?from?student?where?studentName?=?''?or?'1'?=?'1'

'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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How does a HashMap work internally in Java? How does a HashMap work internally in Java? Jul 15, 2025 am 03:10 AM

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

What is the 'static' keyword in Java? What is the 'static' keyword in Java? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

What is a ReentrantLock in Java? What is a ReentrantLock in Java? Jul 13, 2025 am 02:14 AM

ReentrantLock provides more flexible thread control in Java than synchronized. 1. It supports non-blocking acquisition locks (tryLock()), lock acquisition with timeout (tryLock(longtimeout, TimeUnitunit)) and interruptible wait locks; 2. Allows fair locks to avoid thread hunger; 3. Supports multiple condition variables to achieve a more refined wait/notification mechanism; 4. Need to manually release the lock, unlock() must be called in finally blocks to avoid resource leakage; 5. It is suitable for scenarios that require advanced synchronization control, such as custom synchronization tools or complex concurrent structures, but synchro is still recommended for simple mutual exclusion requirements.

See all articles