首页 > 解决方案 > 我试图将 Intellij 连接到数据库(mysql,xampp),由于某种原因,它每次都失败

问题描述

我将 MySQL 驱动程序添加到项目中,由于某种原因,它引发了异常,我创建了一个名为 ex2 的数据库和一个名为 images 的表。

这是我用来在 xampp 中构建数据库的代码:

CREATE DATABASE IF NOT EXISTS `ex2` DEFAULT CHARACTER SET utf8 COLLATE
utf8_general_ci;
USE `ex2`;
CREATE TABLE `images` (
`id` int(128) NOT NULL,
 `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `url` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `images` ADD PRIMARY KEY (`id`);
ALTER TABLE `images` MODIFY `id` int(128) NOT NULL AUTO_INCREMENT;
package com.company;
import java.sql.*;

/**
 * in this class we connect the program to the db we built
 * and insert the info that is given form the function in the MyThread class.
 */
public class DBinsertion {

    Connection dbConn = null;

    public synchronized void Insert(Long Id, String url){
        try {
            String odbcDriver = "com.mysql.jdbc.Driver";
            Class.forName(odbcDriver);
        }
        catch (Exception e) {
            System.out.println("Failed to load the driver");
            return;
        }

        try {
            dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/images?user=root&password=");
            String sql = "INSERT INTO `images` (id,date_added,url) values (?,?,?)";
            PreparedStatement stmt = dbConn.prepareStatement(sql);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            stmt.clearParameters();
            stmt.setLong(1,Id);
            stmt.setTimestamp(2, timestamp);
            stmt.setString(3, url);
            stmt.executeUpdate();
            stmt.close();
        }

        catch (SQLException e){
            System.out.println("Sql");
        }

        finally {
            try {
                if (dbConn != null) { dbConn.close(); }
            } catch (SQLException e) {
                // debugging info
                e.printStackTrace();
            }
        }
    }
}

标签: javamysqlintellij-idea

解决方案


推荐阅读