如何在JAVA中建立MySQL连接

时间:2010-11-13 13:21:03

标签: java mysql netbeans jdbc

我似乎无法将我的Java程序连接到java,我已启动MySQL服务器,在phpMyAdmin中创建了一个数据库。但我对如何使用从MySQL下载的JDBC驱动程序感到困惑。

这是我的代码:

    private void startConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "bank";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
} catch (Exception e) {
    System.out.println("NO CONNECTION =(");
}
}

我在我的JDK-jre \ lib \ ext文件夹中包含了jar文件,但没有。有什么想法吗?

提前致谢。

3 个答案:

答案 0 :(得分:3)

有一点很突出:您没有在URL中指定网络端口。默认端口是3306.所以请尝试:

jdbc:mysql://localhost:3306/

对于网址。

答案 1 :(得分:1)

您必须指定端口。默认为String url = "jdbc:mysql://localhost:3306/";

答案 2 :(得分:0)

private void startConnection()
{
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "bank";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "password";

    try
    {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,userName,password);
        System.out.println("Connected to the database");
        conn.close();
        System.out.println("Disconnected from database");

    }
    catch (Exception e)
    {
        System.out.println("NO CONNECTION =(");
    }
}

这将有效