数据库连接

连接数据库的步骤如下:

  1. 加载驱动程序:在Java代码中加载数据库驱动程序,可以使用Class.forName()方法加载驱动程序类。

  2. 建立数据库连接:创建一个Connection对象,指定数据库的连接信息,包括数据库的URL、用户名和密码。可以使用DriverManager.getConnection()方法来建立连接。

  3. 创建Statement对象:使用Connection对象的createStatement()方法创建一个Statement对象,用于发送SQL语句到数据库并获取执行结果。

  4. 执行SQL语句:使用Statement对象的executeQuery()方法执行SQL查询语句,或者使用executeUpdate()方法执行更新操作,如插入、更新或删除数据。

  5. 处理查询结果:如果执行的是查询语句,可以使用ResultSet对象来获取查询结果。

  6. 关闭数据库连接:使用Connection对象的close()方法关闭数据库连接,释放资源。

下面是一个示例代码,演示如何连接到MySQL数据库:

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.jdbc.Driver");
            
            // 建立数据库连接
            String url = "jdbc:mysql://localhost:3306/mydatabase";
            String username = "root";
            String password = "password";
            Connection connection = DriverManager.getConnection(url, username, password);
            
            // 创建Statement对象
            Statement statement = connection.createStatement();
            
            // 执行查询语句
            String sql = "SELECT * FROM employee";
            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);
            }
            
            // 关闭数据库连接
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值