Mysql and Java

Mysql and Java

We can use Java JDBC to connect to a Mysql database and can retrieve values from the database. Please find the concept of Mysql and Java connection below. Similarly you can establish connection from Java to any database.

Mysql and Java Example

  import java.sql.*;
  public class Mysqlandjava
  public static void main(String[] args)
  System.out.println("MySQL and Java Connection");
  Connection conn = null;
  String link = "jdbc:mysql://localhost:1111/";
  String dbName = "mysqlandjava";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "username";
  String password = "password";
  conn = DriverManager.getConnection(link+dbName,userName,password);
  System.out.println("Connected Successfully!");
  System.out.println("Connection Closed!");
  catch (Exception e)

Connnection is an interface in java.sql package. Databases like MySQL, Oracle, etc can be connected.

Class.forName(String driver) is a static method. This attempts to load class and return the class instance and takes string value (driver) after that matches the class with given string.

DriverManager is a class of Java JDBC driver.

getConnection(String link, String userName, String password) method establishes a database connectivity. 3 parameters are required namely the link, the username and the password.

con.close() is used to close the database connection once the values are retrieved from the database.

printStackTrace() is used to show error message. Message is thrown if connection is failed.
For more details just visit,

Thanks and Best Regards...

No comments:

Post a Comment

My Profile