Skip to content

Instantly share code, notes, and snippets.

@mubbashir10
Created March 16, 2016 23:38
Show Gist options
  • Save mubbashir10/4c2aff59fbbdf2534835 to your computer and use it in GitHub Desktop.
Save mubbashir10/4c2aff59fbbdf2534835 to your computer and use it in GitHub Desktop.
Simple JDBC example to connect to MySQL Server.
/*
About: A simple tutorial showing JDBC connection (to MYSQL Database)
Author: Mubbahsir10
URL: http://mubbashir10.com
*/
//packages/libraries
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
//JDBCExample Class
public class JDBCExample {
//main method
public static void main(String[] argv) {
//initializing
System.out.println("Connecting to MySQL Server...");
//loading JDBC driver
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e){
System.out.println("JDBC Driver not found!");
e.printStackTrace();
return;
}
//status
System.out.println("MySQL JDBC Driver Registered!");
//connection object
Connection connection = null;
//making connection
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root", "test");
}
catch (SQLException e) {
e.printStackTrace();
return;
}
//connection success
if (connection != null) {
System.out.println("MySQL connection established successfully!");
}
//connection failure
else {
System.out.println("Error establishing MySQL connection!");
}
//closing connection
try{
connection.close();
}
catch(SQLException se){
se.printStackTrace();
return;
}
}//main method
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment