Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MySQL Java Connection and Usage

MySQL Java Connection and Usage

MySQL is one of the most popular open-source relational databases, while Java is the most commonly used programming language in enterprise application development. Combining Java with MySQL allows you to build powerful data-driven applications.

This article will introduce in detail how to connect to and use the MySQL database in Java programs, including:

This article introduces the basic steps of connecting to and using the MySQL database in Java, including:


Preparation

Download the MySQL JDBC Driver

Java interacts with databases through JDBC (Java Database Connectivity) technology. To connect to MySQL, you need to download the MySQL Connector/J driver:

  1. Access the MySQL Connector/J download page
  2. Choose a driver version compatible with your Java version
  3. Download the JAR file (such as mysql-connector-java-8.0.xx.jar)

Add the Driver to the Project

Depending on the development tool or build tool you use (such as Eclipse, IntelliJ IDEA, Maven, or Gradle), add the downloaded JAR file to the project's classpath.


Establish a database connection

Loading the Driver

In Java code, you first need to load the MySQL JDBC driver:

Example

try

{

   

Class

.

forName

(

"com.mysql.cj.jdbc.Driver"

)

;

}

catch

(

ClassNotFoundException

e

)

{

   

System

.

out

.

println

(

"MySQL JDBC driver not found"

)

;

    e.

printStackTrace

(

)

;

}

Create a Connection

Use DriverManager.getConnection()method to establish a connection with the database:

Example

String

url

=

"jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC"

;

String

username

=

"your_username"

;

String

password

=

"your_password"

;

try

{

   

Connection

connection

=

DriverManager

.

getConnection

(

url, username, password

)

;

   

System

.

out

.

println

(

"Database connection successful!"

)

;

}

catch

(

SQLException

e

)

{

   

System

.

out

.

println

(

"Database connection failed"

)

;

    e.

printStackTrace

(

)

;

}

3.2.1 Connection Parameter Description


Execute the SQL operation

Creating a Statement Object

The Statement object is used to execute static SQL statements:

Example

Statement

statement

=

connection.

createStatement

(

)

;

Execute query

Use executeQuery() method to execute a SELECT statement:

Example

String

sql

=

"SELECT * FROM table_name"

;

ResultSet

resultSet

=

statement.

executeQuery

(

sql

)

;

while

(

resultSet.

next

(

)

)

{

   

int

id

=

resultSet.

getInt

(

"id"

)

;

   

String

name

=

resultSet.

getString

(

"name"

)

;

   

System

.

out

.

println

(

"ID: "

id

", Name: "

name

)

;

}

Executing Updates

Use executeUpdate() method to execute INSERT, UPDATE, or DELETE statements:

Example

String

insertSQL

=

"INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')"

;

int

rowsAffected

=

statement.

executeUpdate

(

insertSQL

)

;

System

.

out

.

println

(

"Number of affected rows: "

rowsAffected

)

;

Using PreparedStatement

PreparedStatement can prevent SQL injection and improve performance:

Example

String

sql

=

"INSERT INTO users (name, email) VALUES (?, ?)"

;

PreparedStatement

preparedStatement

=

connection.

prepareStatement

(

sql

)

;

preparedStatement.

setString

(

1

,

"Zhang San"

)

;

preparedStatement.

setString

(

2

,

"zhangsan@example.com"

)

;

int

rowsInserted

=

preparedStatement.

executeUpdate

(

)

;

System

.

out

.

println

(

"Number of inserted rows: "

rowsInserted

)

;


Transaction management

Basic concepts

A transaction is a group of SQL operations that either all succeed or all fail.

Transaction Operation Example

Example

try

{

   

// Disable auto-commit

    connection.

setAutoCommit

(

false

)

;

   

   

// Execute multiple SQL operations

    statement.

executeUpdate

(

"UPDATE accounts SET balance = balance - 100 WHERE id = 1"

)

;

    statement.

executeUpdate

(

"UPDATE accounts SET balance = balance + 100 WHERE id = 2"

)

;

   

   

// Commit the transaction

    connection.

commit

(

)

;

   

System

.

out

.

println

(

"Transaction executed successfully"

)

;

}

catch

(

SQLException

e

)

{

   

// Roll back when an error occurs

    connection.

rollback

(

)

;

   

System

.

out

.

println

(

"Transaction failed, rolled back"

)

;

    e.

printStackTrace

(

)

;

}

finally

{

   

// Restore auto-commit

    connection.

setAutoCommit

(

true

)

;

}


Close resources

Why Resources Need to Be Closed

Database connections are limited resources and must be closed after use to avoid resource leaks.

How to Close Resources Properly

Example

try

{

   

if

(

resultSet

!=

null

)

resultSet.

close

(

)

;

   

if

(

statement

!=

null

)

statement.

close

(

)

;

   

if

(

connection

!=

null

)

connection.

close

(

)

;

}

catch

(

SQLException

e

)

{

    e.

printStackTrace

(

)

;

}

6.3 Using try-with-resources

Java 7+ can use try-with-resources to automatically close resources:

Example

try

(

Connection

conn

=

DriverManager

.

getConnection

(

url, username, password

)

;

     

Statement

stmt

=

conn.

createStatement

(

)

;

     

ResultSet

rs

=

stmt.

executeQuery

(

"SELECT * FROM users"

)

)

{

   

   

while

(

rs.

next

(

)

)

{

       

// Handle the result

   

}

}

catch

(

SQLException

e

)

{

    e.

printStackTrace

(

)

;

}


Best Practices

Use Connection Pools

In production environments, connection pools (such as HikariCP, c3p0) should be used to manage database connections:

Example

// HikariCP example

HikariConfig config

=

new

HikariConfig

(

)

;

config.

setJdbcUrl

(

"jdbc:mysql://localhost:3306/your_database"

)

;

config.

setUsername

(

"Username"

)

;

config.

setPassword

(

"password"

)

;

HikariDataSource dataSource

=

new

HikariDataSource

(

config

)

;

Connection

connection

=

dataSource.

getConnection

(

)

;

Handle Exceptions

Handle SQL exceptions properly and provide meaningful error messages:

Example

try

{

   

// Database operation

}

catch

(

SQLException

e

)

{

   

System

.

err

.

println

(

"SQL error: "

e.

getMessage

(

)

)

;

   

System

.

err

.

println

(

"SQL state: "

e.

getSQLState

(

)

)

;

   

System

.

err

.

println

(

"Error code: "

e.

getErrorCode

(

)

)

;

}

7.3 Using the DAO Pattern

Encapsulate data access logic in a Data Access Object (DAO) to improve code maintainability:

Example

public

class

UserDao

{

   

private

Connection

connection

;

   

   

public

UserDao

(

Connection

connection

)

{

       

this

.

connection

=

connection

;

   

}

   

   

public

User getUserById

(

int

id

)

throws

SQLException

{

       

String

sql

=

"SELECT * FROM users WHERE id = ?"

;

       

try

(

PreparedStatement

stmt

=

connection.

prepareStatement

(

sql

)

)

{

            stmt.

setInt

(

1

, id

)

;

           

ResultSet

rs

=

stmt.

executeQuery

(

)

;

           

if

(

rs.

next

(

)

)

{

               

return

new

User

(

rs.

getInt

(

"id"

)

, rs.

getString

(

"name"

)

)

;

           

}

       

}

       

return

null

;

   

}

}

By mastering these fundamentals, you can already start using the MySQL database in Java applications. As you gain experience, you can further study more advanced topics such as connection pools, ORM frameworks (such as Hibernate, MyBatis), and so on.