如何使用Java连接到数据库连接

Jei*_*man 4 java database xampp jdbc

我想知道如何连接到Xampp MySQL中托管的数据库。

到目前为止,这就是我要连接的Java代码中的内容,但是我不确定自己在做什么。

public static void main(String[] args) {
    try {
        Connection con = DriverManager.getConnection( host, username, password );
        String host = "jdbc:derby://localhost:1527/Employees";
        String uName = "root";
        String uPass= "password";
    }
    catch ( SQLException err ) {
    System.out.println( err.getMessage( ) );
    }

}
Run Code Online (Sandbox Code Playgroud)
  1. 主机URL是什么?
  2. 我是否需要JDBC Jar文件才能连接到数据库?

我已经通过phpMyAdmin设置了数据库和表。只是不知道如何进行。

我正在使用Netbeans编写Java代码以连接到通过Xampp PHPMyAdmin创建的本地数据库。

最后,我想用Java创建数据库连接并在IDE中调出表。希望能有所帮助。

Sug*_*lai 5

这是项目结构

项目结构

试试这个

更新资料

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your MySQL JDBC Driver?");
        e.printStackTrace();
        return;
    }

    System.out.println("MySQL JDBC Driver Registered!");
    Connection connection = null;

    try {
        connection = DriverManager
        .getConnection("jdbc:mysql://localhost:3306/testspring","root", "password");

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;
    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }
}
Run Code Online (Sandbox Code Playgroud)

它为我工作

我从Java2s.com下载jar

参考