云主机测评网云主机测评网云主机测评网

云主机测评网
www.yunzhuji.net

java连接mysql数据库代码

java,import java.sql.Connection;,import java.sql.DriverManager;,import java.sql.SQLException;,,public class MySQLConnection {, public static void main(String[] args) {, String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC";, String user = "用户名";, String password = "密码";,, try {, Class.forName("com.mysql.cj.jdbc.Driver");, Connection connection = DriverManager.getConnection(url, user, password);, System.out.println("连接成功");, connection.close();, } catch (ClassNotFoundException e) {, e.printStackTrace();, } catch (SQLException e) {, e.printStackTrace();, }, },},

以下是使用Java连接MySQL数据库的详细代码,包括小标题和单元表格:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLConnectionDemo {
    public static void main(String[] args) {
        // 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 连接数据库
        String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC";
        String user = "用户名";
        String password = "密码";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        // 执行查询操作
        String query = "SELECT * FROM 表名";
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            while (resultSet.next()) {
                System.out.println("字段1:" + resultSet.getString("字段1") + ",字段2:" + resultSet.getString("字段2"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

请将上述代码中的数据库名用户名密码表名字段1字段2等替换为实际的值。

打赏
版权声明:主机测评不销售、不代购、不提供任何支持,仅分享信息/测评(有时效性),自行辨别,请遵纪守法文明上网。
文章名称:《java连接mysql数据库代码》
文章链接:https://www.yunzhuji.net/internet/178072.html

评论

  • 验证码