Java Maven jdbc连接mysql数据库

创建maven项目
在pom.xml中添加依赖

<dependencies>
    <!-- 其他依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version> <!-- 请确保使用最新的MySQL JDBC驱动版本 -->
    </dependency>
</dependencies>

连接到mysql数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLConnectionExample {
    public static void main(String[] args) {
        // MySQL数据库连接信息
        String url = "jdbc:mysql://localhost:3306/your_database";
        String user = "your_username";
        String password = "your_password";

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

            // 尝试建立连接
            Connection connection = DriverManager.getConnection(url, user, password);

            if (connection != null) {
                System.out.println("成功连接到数据库!");
                // 在这里可以执行各种数据库操作
                // 例如:执行查询、插入、更新、删除等操作

                // 记得在完成后关闭连接
                connection.close();
            }
        } catch (ClassNotFoundException e) {
            System.err.println("无法找到MySQL JDBC驱动程序: " + e.getMessage());
        } catch (SQLException e) {
            System.err.println("连接数据库时发生错误: " + e.getMessage());
        }
    }
}

Sitemap · Rss

津ICP备2021004480号-3