我的连接代码不工作为什么?

时间:2022-01-25 20:18:50

why is it my Connection code not working? I have everything right password,user, and the host and the driver but why is it not working??

为什么我的连接代码不能工作?我有所有正确的密码,用户,主机和驱动,但是为什么它不能工作?

 import java.sql.*;

public class Connection {

    public  String url = "jdbc:mysql://localhost:3306/Testdb";
    public String driver = "com.mysql.jdbc.Driver";
    public String user = "root";
    public String pass = "123192";

    public void JdbcConnection(){

        try{
            Class.forName(driver);
        }catch(Exception e){
            e.printStackTrace();
        }

        try{
            Connection con = DriverManager.getConnection(url,user,pass);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

2 个解决方案

#1


1  

Please change the name of your class (it must not a Connection especially when you import the java.sql.*) and you need to specify the username and password while obtaining a connection.

请更改类的名称(必须不是连接,特别是在导入java.sql.*时),并且在获取连接时需要指定用户名和密码。

public class TestConnection {
   ....
   Connection con = DriverManager.getConnection(url,user,pass);
}

#2


2  

The problem is that "Connection con" should be of type java.sql.Connection, but since your own class is called Connection, your code thinks you are making a reference to that instead of java.sql.Connection. You can disambiguate the type of con by using the full class name like so:

问题是“连接con”应该是java.sql类型。连接,但是由于您自己的类被称为Connection,所以您的代码认为您是在引用它,而不是java.sql.Connection。您可以使用完整的类名,如:

try{
    java.sql.Connection con = DriverManager.getConnection(url,user,pass);
}catch(Exception e){
    e.printStackTrace();
}

#1


1  

Please change the name of your class (it must not a Connection especially when you import the java.sql.*) and you need to specify the username and password while obtaining a connection.

请更改类的名称(必须不是连接,特别是在导入java.sql.*时),并且在获取连接时需要指定用户名和密码。

public class TestConnection {
   ....
   Connection con = DriverManager.getConnection(url,user,pass);
}

#2


2  

The problem is that "Connection con" should be of type java.sql.Connection, but since your own class is called Connection, your code thinks you are making a reference to that instead of java.sql.Connection. You can disambiguate the type of con by using the full class name like so:

问题是“连接con”应该是java.sql类型。连接,但是由于您自己的类被称为Connection,所以您的代码认为您是在引用它,而不是java.sql.Connection。您可以使用完整的类名,如:

try{
    java.sql.Connection con = DriverManager.getConnection(url,user,pass);
}catch(Exception e){
    e.printStackTrace();
}