下面是一个简单的Java连接MySQL数据库的代码示例:

import java.sql.*;

public class DatabaseConnection {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 连接MySQL数据库
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");

            // 执行查询语句
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

            // 处理查询结果
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

上面的代码首先通过DriverManager.getConnection()方法连接了一个名为mydatabase的MySQL数据库,并使用root用户和password密码进行身份验证。然后,它创建了一个Statement对象,并使用executeQuery()方法执行了一个查询语句,该语句将所有行从mytable表中选择出来。最后,它遍历了ResultSet对象中的每一行,并输出了每一行的idnameage列的值。

注意,上面的代码需要引入java.sql包,并且需要下载并安装MySQL JDBC驱动程序。

写一段java连接数据库的代码

原文地址: http://www.cveoy.top/t/topic/biLc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录