当前位置: 首页 > 图灵资讯 > 技术篇> java连接Mysql

java连接Mysql

来源:图灵教育
时间:2024-03-10 16:20:24

Class加载数据库驱动程序.forName("com.mysql.jdbc.Driver");创建连接Stringng的数据库 url = "jdbc:mysql://localhost:3306/testdb";String user = "root";String password = "password";Connection conn = DriverManager.getConnection(url, user, password);这里的 url 格式为 jdbc:mysql://host:port/database,其中 host 和 port 分别是 MySQL 服务器的主机名和端口号,database 表示连接的数据库名称。user 和 password 是登录 MySQL 用户名和密码需要数据库。

创建 Statement 对象,执行 SQL 句子Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");while (rs.next()) {// 这里处理查询结果},创建了一个 Statement 对象 stmt 用于执行 SQL 查询句子并通过 executeQuery() 方法执行查询,保存查询结果 ResultSet 对象 rs 中间,然后使用 while 处理循环遍历结果集。

关闭连接rs的数据库.close();stmt.close();conn.close();使用数据库连接后,应及时关闭并释放资源。

完整代码:

public class MySQLConnectionDemo { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null;

try { // 加载MySQL驱动程序 Class.forName("com.mysql.cj.jdbc.Driver");

// 创建数据库连接 String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; connection = DriverManager.getConnection(url, username, password);

// 创建Statement对象 statement = connection.createStatement();

// 执行查询语句 String sql = "SELECT * FROM mytable"; resultSet = statement.executeQuery(sql);

// 查询结果的处理 while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); float price = resultSet.getFloat("price");

System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭连接和释放资源 try { if (resultSet != null) { resultSet.close(); } if (statement != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }}

上一篇:

Java流式编程

下一篇:

Java Web 进阶