开发者

How to make a MySQL Connection in JAVA

I can't seem to get a connection made on my Java program to java, I have started the MySQL Server, made a database in phpMyAdmin. But I'm confused on how I should use the JDBC Driver that I downloaded from MySQL.

Here's my code:

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

I had included the jar file in my JDK - jre\lib\ext folder but nothing. Any ideas?

Thanks in advance.


One thing stands out: you haven't specified a network port in the URL. The default port is 3306. So try:

jdbc:mysql://localhost:3306/

For the URL.


You have to specify the port. It's String url = "jdbc:mysql://localhost:3306/"; by default.


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

This will work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜