Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JAVA中建立MySQL连接_Java_Mysql_Netbeans_Jdbc - Fatal编程技术网

如何在JAVA中建立MySQL连接

如何在JAVA中建立MySQL连接,java,mysql,netbeans,jdbc,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.j

我似乎无法在我的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文件,但什么都没有。有什么想法吗


提前感谢。

有一点很突出:您没有在URL中指定网络端口。默认端口为3306。因此,请尝试:

jdbc:mysql://localhost:3306/

对于URL。

您必须指定端口。它是
String url=“jdbc:mysql://localhost:3306/";默认情况下

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 =(");
    }
}

这将起作用

此代码的控制台输出是什么?您得到的错误是什么?代码对我来说很好。要获得准确的错误,请使用
e.printStackTrace()在catch子句中。在异常处理程序中,请打印堆栈跟踪或至少
e.getMessage()
!我已经将stacktrace放在了一个粘贴箱中:@Sandeep Bansal:u是否在构建路径中包含了com.mysql.jdbc.Driver?尝试使用端口号,仍然无法工作。我已经在上面的评论中发布了堆栈跟踪。2件事:首先,检查MySQL驱动程序的jar文件是否在classpath或jre\lib\ext文件夹中。其次,查看jar文件内部(例如,使用“jar tf”),检查其中是否有“com/mysql/jdbc/Driver.class”。此外,如果您的Java应用程序在将mysql驱动程序jar添加到类路径后没有重新启动,则需要重新启动它。虽然这不是完整答案,就像在IDE中添加jar文件一样。你的答案更接近,所以你明白了。谢谢Sandeep。很高兴我能帮忙。