import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySQLExample {
// JDBC URL, username, and password of MySQL server
private static final String URL = "jdbc:mysql://localhost:3306/yourdatabase";
private static final String USER = "yourusername";
private static final String PASSWORD = "yourpassword";
// JDBC variables for opening and managing connection
private static Connection connection;
public static void main(String[] args) {
try {
// Establish the connection to the database
connection = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("Connected to the database!");
// Create a PreparedStatement to execute a query
String query = "SELECT id, name FROM users WHERE age > ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, 18);
// Execute the query and get the result set
ResultSet resultSet = preparedStatement.executeQuery();
// Process the result set
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Close the resources
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
// Handle SQL exceptions
e.printStackTrace();
} finally {
// Ensure the connection is closed
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
DriverManager.getConnection()方法建立与MySQL数据库的连接,需要提供数据库的URL、用户名和密码。PreparedStatement来执行SQL查询,可以防止SQL注入,并且可以更方便地设置查询参数。ResultSet对象进行处理,遍历每一行数据并提取字段值。ResultSet、PreparedStatement和Connection,以释放资源并避免潜在的内存泄漏。希望这段代码和解释对你有帮助!
上一篇:java连接mysql数据库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站