简体   繁体   English

使用Java连接到MySql数据库

[英]Connecting to MySql Database using Java

So I've been teaching myselft mysql and am trying to integrate it into my Java code. 因此,我一直在自学mysql,并试图将其集成到我的Java代码中。 I've looked at some past code snippets and tutorials and I can't seem to figure out why my code is incorrect. 我看了一些过去的代码片段和教程,但似乎无法弄清楚为什么我的代码不正确。 (removed password for obvious reasons) (出于明显原因删除了密码)

Here's what I'm using to connect 这是我用来连接的东西

  public static void connectionToMySql(){
    String host = "mysql9.000webhost.com";
    String username = "a9808220_pin";
    String pass = "";
    try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection connection = DriverManager.getConnection(host,username,pass);
      /*insert code*/
        connection.close();
        System.out.println("It worked :)");

    } catch (Exception e) {
        System.out.println("Something went wrong :(");
        e.printStackTrace();
    }
}

I get an exception that there's no suitable driver. 我得到一个例外,没有合适的驱动程序。 I'm not sure why because I have the jar downloaded and pathed correctly 我不确定为什么,因为我下载了jar并正确进行了路径设置

String host should be like 字符串主机应该像

String host = "jdbc:mysql:ip:port"//ip or hostname

example code that works for me... 适用于我的示例代码...

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1433;"
                 +"databaseName=test;"
                 +"user=sa;"
                 +"password=xxxxx;");
         System.out.println("connected");

Your connection should be a JDBC URL in the form 您的连接应为JDBC URL,格式为

String url = "jdbc:mysql://mysql9.000webhost.com:3306/";

Now in order for this to work you should: 现在,为了使它起作用,您应该:

1) Verify that mySQL is running on the host mysql9.000webhost.com 1)验证mySQL在主机mysql9.000webhost.com上运行

2) Verify that the port is the default port ie 3306, if not change the code above to use the right port 2)确认端口是默认端口,即3306,如果未更改上面的代码以使用正确的端口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM