0

我刚开始使用 Connector/J 尝试通过本地主机与 XAMPPs MySQL 建立基本连接。我认为我做得对,但我发现的说明是旧的,这意味着我无法将我的代码与完美运行的东西匹配并从那里适应,因为某些部分,如驱动程序 URL 与说明不同。附上代码:

package dbcaller;

import com.mysql.cj.xdevapi.Statement;        // in other versions these had a diff name
import com.sun.jdi.connect.spi.Connection;    // these two are the biggest issues here.
import java.sql.DriverManager;
import java.sql.SQLException;


/*
 * @author Hamza Abdulhaqq
 */
public class Database {
    private Connection conn;
    private Statement statement;
    
    public Connection openConnection() throws SQLException{
        if(conn == null)
        {
        String url = "remote/";
        String dbName = "testdb";
        String driver = "com.mysql.cj.jdbc.Driver";
        String userName = "root";
        String password = "";
        
        try
        {
            Class.forName(driver); // this looks good
            this.conn = (Connection)DriverManager.getConnection(url+dbName,userName,password);
            
            System.out.println("CONNECTION SUCCESSFUL");
        }
        
        catch (ClassNotFoundException | SQLException sqle)
        {
            System.out.println("CONNECTION Failed");
        }
    }

    return conn;
    }
    
}

我实际上在同一个包的另一个文件中运行它。

package dbcaller;

import java.sql.SQLException;

/**
 *
 * @author Hamza Abdulhaqq
 */
public class DBcaller {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException {
        Database db = new Database();
        db.openConnection();
    }
    
}

我的库中有“mysql-connector-java-8.0.27.jar”。所以我不确定接下来要检查什么。我发现我现在使用的代码应该是最新的,所以它可能是别的东西。

4

0 回答 0