2

Hi guy i want to connect to my database on my website using java. i wonder what should i put in URL:

cnt=DriverManager.getConnection(DB_URL, DB_UID,DB_PWD);

Can you guy give me an example how to connect Mysql Database on website using java?

i have try to use:

import java.sql.*;

public class CreateConnect {


public final static String DB_DRIVER="com.mysql.jdbc.Driver";
public final static String SEVER_HOST="mysite";
public final static String PORT_NUM="3306";

public final static String DB_NAME="studentdb";
public final static String DB_UID="root";
public final static String DB_PWD="root";

public final static String DB_URL="jdbc:mysql://"+SEVER_HOST+":"+PORT_NUM+"/"+DB_NAME;

private static Connection cnt;

public static Connection getConnection()
{

    try
    {

        cnt=DriverManager.getConnection(DB_URL, DB_UID,DB_PWD);
        System.out.println("Connection Successfully");
    }
    catch(SQLException e)
    {
        System.out.println("Connection ERROR");
        e.printStackTrace();
    }

    return cnt;
}
6
  • 2
    Then what is the error/exception ? Commented Dec 24, 2013 at 12:49
  • do u want to connect to database were u hosted ur website.am i right? Commented Dec 24, 2013 at 12:50
  • its usually localhost:port/db_name Commented Dec 24, 2013 at 12:54
  • Is it not problem that driver class is not loaded. I do not see use of DB_DRIVER. Something like Class.forName(DB_DRIVER) or it is done somewhere else? If you would like to use this code on web with many threads you can have problem. Commented Dec 24, 2013 at 13:01
  • in between u did not add Class.forName() for initializing the driver? Commented Dec 24, 2013 at 13:09

2 Answers 2

1

I guess I understood your problem but if you could tell me the error that would have been more helpful to debug.

Add this line before calling getConnection method.

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

I hope it should work now.

Sign up to request clarification or add additional context in comments.

Comments

0

The below reference can help you connect to the database which is hosted.you have to provide the IPaddress of the site and port number 3306 to connect to the database.

JDBC: connect to remote mySQL database?

3 Comments

port 3306 is used in the code, SEVER_HOST should be changed to a real hostname of server running my sql
SERVER_HOST should contain the IP address of the host.
preciselly ip or DNS name (hostname) if DNS work on the server that runs the java code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.