Create Mysql Database JDBC connection in Java.
Points To Remember
- Download Mysql Java Connector by clicking on the link.
- Put the above downloaded jar file in the lib folder of your project.
Code : Mysql JDBC connection in Java
import java.sql.Connection; import java.sql.DriverManager; public class JavaMysqlConnection { private String host = "localhost:3306"; // For running on localhost private String db = "databaseName"; private String userName = "userName"; private String password = "password"; public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://"+ host +"/"+db,userName, password); return conn; }catch(Exception e){ e.printStackTrace(); } return null; } } public class Test{ public static void main(String[] argv) { Connection conn = new JavaMysqlConnection().getConnection(); if(conn == null) System.out.println("Connection was not established"); else System.out.println("Connection is successfully established"); } }
This is a very generic code that you can use in both your standalone projects and web based projects. Whenever you need to get a connection to database, you just need to create an object of class JavaMysqlConnection and call its getConnection() method.
No comments: