Connect MySQL with JDBC: Java Guide
JDBC (Java Database Connectivity) is the standard method in Java for accessing databases, allowing connection to various types of databases, including MySQL.
The following steps are necessary to connect to the MySQL database:
- Load the database driver: Use Class.forName(“com.mysql.jdbc.Driver”) to load the MySQL database driver.
- Establishing a database connection: Use the DriverManager.getConnection(url, username, password) method to establish a connection with the database, where url is the connection address of the database, and username and password are the username and password of the database.
- Create a Statement object: Use the Connection.createStatement() method to create a Statement object for executing SQL statements.
- Execute SQL statement: Use the executeQuery(sql) method of the Statement object to run SQL queries, and use the executeUpdate(sql) method to run SQL update statements.
- Handling query results: Use the ResultSet object to handle query results, use the ResultSet.next() method to traverse the result set, and use methods like ResultSet.getString() and getInt() to retrieve field values.
- Close the database connection: Use the Connection.close() method to close the database connection.
Here is a sample code demonstrating how to connect to a MySQL database and execute a query statement.
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, username, password);
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行SQL查询语句
String sql = "SELECT * FROM users";
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
// 关闭数据库连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above are the detailed steps for connecting to a MySQL database. Connecting to other types of databases is similar, just requiring the replacement of the database driver and connection address.