Java MySQL Connection: JDBC Tutorial
In Java, connecting to MySQL is typically achieved using JDBC (Java Database Connectivity). Below is a simple example code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
// JDBC连接URL,数据库名为test
String url = "jdbc:mysql://localhost:3306/test";
// 数据库用户名和密码
String username = "root";
String password = "root";
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立与数据库的连接
Connection conn = DriverManager.getConnection(url, username, password);
// 执行SQL查询等操作
// ...
// 关闭连接
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In the example above, first load the MySQL driver, then establish a connection to the database using the DriverManager.getConnection method, where the URL is the connection URL, username is the database username, and password is the database password. You can then execute SQL queries and operations, and remember to close the connection when finished.