Java Program to Connect To Database.


Below is the Java Program To connect to Database

Here the DataBase used is Mysql database Steps to follow




  • Download the Mysql connector from the internet.

  • import it in your project.

  • Right click on project->Properties->Java build path.

  • In libraries select Add external jars on the right side menu.

  • select and add mysql connector that you downloaded.

  • Go to tab order and export and select the mysql connector checkbox.




import java.sql.*;
public class ConnectDatabase {

public static void main(String[] args) {

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

try
   {

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root@123");

System.out.println("Connected");

}
    catch (SQLException e)
   {

System.out.println("Bad Connection Request");

}


}


}



Output.

Connected.



Explaination

  • com.mysql.jdbc.Driver- driver class for Mysql;
  • DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root@123");-
Here jdbc is API, mysql is database, localhost is the server name. It can also be an IP address, 3306 is the port number. And root is username , root@123 is a password.
Java Program to Connect To Database. Java Program to Connect To Database. Reviewed by LanguageExpert on August 25, 2017 Rating: 5

No comments