java - 我试图将 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();
}
}
}
}
解决方案
推荐阅读
- hololens - 如何在 Hololens 2 上获得睡眠设置?
- reactjs - 如何更改 TextField 中清除按钮的颜色?
- c# - CefSharp:登录到 WPF 站点后下载文件
- r - ZONAL STATISTIC:函数 EXTRACT 中的错误(替换长度为 0)
- lit-element - vaadin-grid cellClassNameGenerator 不呈现类
- pip - pip install PyBluez,安装出错
- regex - .htaccess 头痛:将根文件夹重定向到 A,这些文件夹到 B,忽略其余的
- vue.js - vue 面包屑未将完整路径设置为链接
- azure - Azure 认知搜索接收器 Kafka 连接器不工作
- python-3.x - 如何使用 discord.py 从 VoiceChannel 录制音频?