Java – MySQL Database Connection
package <1. type your package name>;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import java.sql.*;
public class databaseConnection {
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost:3306/<2. add your database name>;
final static String USER = "<3.username of the server (username of localhost)>";
final static String PASS ="<4. password of the server>";
public static Connection connection(){
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
return null;
}
}
- First Create the class call “databaseConnection”
- Then Copy the code
- Fill the steps 1 to 4
- <1. type your package name>
- <2. add your database name>
- <3.username of the server (username of localhost)>
- <4. password of the server>
Then we have to add below libraries,
- mysql jdbc 5.1 5 jar : http://www.java2s.com/Code/Jar/m/Downloadmysqlconnectorjava5115jar.htm
- Import the MySQL JDBC Driver
- Run the Code
