How we connect to a database in JDBC?

How we connect to a database in JDBC?

Senior Developer Asked on June 19, 2017 in JAVA.
Add Comment
1 Answer(s)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;
public class DBConnection {

public static void main(String[] args) {

String dbURL = "jdbc:mysql://localhost:3306/demo";

String user = "root";

String password = "";

Connection con = null;

try {

con = DriverManager.getConnection(dbURL, user, password);

if (con != null) {

System.out.println("Database Connected.");

}

} catch (SQLException ex) {

System.out.println("Error! User OR password is invalid..");

ex.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

} catch (SQLException ex) {

ex.printStackTrace();

}

}

}

}

}

IT Head Answered on June 29, 2017.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.