How to connect to a remote MySQL database with Java?

后端 未结 8 1440
暗喜
暗喜 2020-12-02 11:16

I am trying to create a JSF application using the Eclipse IDE. I am using a remote mySQL server as my database. How do I connect to this remote database for creating tables

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 12:07

    You need to pass IP/hostname of the rempote machine in the connection string.

    import java.sql.*;
    import javax.sql.*;
    
    public class Connect
    {
       public static void main (String[] args)
       {
           Connection conn = null;
    
           try
           {
    
               String url = "jdbc:mysql://localhost:3306/mydb";
               Class.forName ("com.mysql.jdbc.Driver");
               conn = DriverManager.getConnection (url,"root"," ");
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               e.printStackTrace();
    
           }
           finally
           {
               if (conn != null)
               {
                   try
                   {
                       conn.close ();
                       System.out.println ("Database connection terminated");
                   }
                   catch (Exception e) { /* ignore close errors */ }
               }
           }
       }
    }
    

提交回复
热议问题