java - 无法通过 Java 连接到 MySQL
问题描述
我正在尝试通过 Java 程序向本地计算机上运行的 MySQL 数据库添加一个条目。我一辈子都无法让程序连接到数据库,我得到一个反复出现的错误:
java.sql.SQLException:找不到适合 jdbc 的驱动程序:mysql://localhost/dtca
我读过的所有内容都在说 JDBC 不在类路径上。我已经将它添加到Java文件的根文件夹中,放在lib文件夹中,Java文件放在src文件夹中。我尝试使用 IntelliJ 而不是 Visual Studio Code,但没有成功。
我绝不是专家,如果这是愚蠢的事情,我很抱歉。我在下面附上了我的代码。
package src;
import java.sql.*;
public class insertCustomer{
public static void main(String[] args) {
//database URL
final String DATABASE_URL = "jdbc:mysql://localhost/dtca";
Connection connection = null;
PreparedStatement pstat = null;
String firstname = "Daniel";
String lastname = "Turner";
String addressLine1 = "Garryhinch Cross";
String addressLine2 = "Garryhinch";
String city = "Portarlington";
String county = "Laois";
String postcode = "Eire";
String email = "danielt@live.ie";
String contactNumber = "0838068795";
int i=0;
try {
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, "root","**********");
//create Prepared Statement for inserting into table
pstat = connection.prepareStatement( "INSERT INTO Customers (FirstName, LastName, AddressLine1, AddressLine2, City, County, Postcode, E-mail, ContactNumber) VALUES (?,?,?,?,?,?,?,?,?)");
pstat.setString(1,firstname);
pstat.setString(2,lastname);
pstat.setString(3,addressLine1);
pstat.setString(4,addressLine2);
pstat.setString(5,city);
pstat.setString(6,county);
pstat.setString(7,postcode);
pstat.setString(8,email);
pstat.setString(9,contactNumber);
i = pstat.executeUpdate();
System.out.println(i + " record successfully added to the database");
}
catch(SQLException sqlException ) {
sqlException . printStackTrace () ;
}
finally {
try{
pstat. close () ;
connection. close () ;
}
catch ( Exception exception ){
exception . printStackTrace () ;
}
}
} // end main
} // end class
解决方案
首先,您缺少端口。通常对于 mysql 它是 3306,所以你的 url 应该是这样的:DATABASE_URL = "jdbc:mysql://localhost:3306/dtca";
更重要的是,您应该在使用它之前注册您的驱动程序。你可以看看这个教程:JDBC
推荐阅读
- spring-boot - 如何验证电子邮件spring boot thymeleaf
- oracle - 没有选择行 sql developer
- python - 我收到一条消息“分配前引用了局部变量‘缓存’
- drop-down-menu - 我的博客下拉子菜单在悬停时消失
- reactjs - 异步调用循环不等待解决
- flutter - 我应该担心 Flutter 和 Dart 版本不同吗?
- bash - GitHub Action: bash 脚本 grep 匹配失败但在本地工作
- flutter - 以全局方式将骆驼案转换为蛇案
- java - 无法测试没有内容类型的 PUT 请求
- javascript - 我正在尝试使用“导入”,但出现了不和谐的模块错误