无法通过Java连接到MySQL

无法通过Java连接到MySQL,java,mysql,jdbc,Java,Mysql,Jdbc,我试图通过Java程序向本地机器上运行的MySQL数据库添加一个条目。我一辈子都无法让程序连接到数据库。我遇到了一个反复出现的错误: java.sql.SQLException:未找到适合jdbc的驱动程序:mysql://localhost/dtca 我读到的所有内容都是说JDBC不在类路径上。我已经将它添加到Java文件的根文件夹中,将它放在lib文件夹中,并将Java文件放在src文件夹中。我尝试使用IntelliJ而不是Visual Studio代码,但没有成功 我绝对不是专家,如果这是

我试图通过Java程序向本地机器上运行的MySQL数据库添加一个条目。我一辈子都无法让程序连接到数据库。我遇到了一个反复出现的错误:

java.sql.SQLException:未找到适合jdbc的驱动程序:mysql://localhost/dtca

我读到的所有内容都是说JDBC不在类路径上。我已经将它添加到Java文件的根文件夹中,将它放在lib文件夹中,并将Java文件放在src文件夹中。我尝试使用IntelliJ而不是Visual Studio代码,但没有成功

我绝对不是专家,如果这是件愚蠢的事,我很抱歉。我在下面附上了我的代码

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的url是3306,所以您的url应该如下所示:DATABASE_url=“jdbc:mysql://localhost:3306/dtca";


更重要的是,你应该在使用之前注册你的驱动程序。您可以查看本教程:

如果答案不能为您解决问题,请附加错误-我有一个mysql配置,如下所示。请说明您是如何执行程序的。当驱动程序不在运行时类路径上时会发生这种情况(例如,您需要使用
java-cp;mysql-connector-j.jar.Program
)。另外,有一个名为
src
的包似乎表明您的项目布局格式不正确。我猜驱动程序没有加载到类路径中。尝试使用
-verbose:class
参数运行该程序,以显示所有加载的类,并查看mysql驱动程序是否存在于输出中。现在阅读教程时,我在前面尝试过将端口添加到字符串中,这是我的一些课程作业,我正在和一个同学交谈,他没有指定端口,并且有几乎相同的代码,它正在工作。感谢您的快速响应。完全不需要指定端口。未指定时,MySQL连接器/J驱动程序将默认为端口3306。