Make a Connection between Java and MySQL
Step by step on how to make a connection between Java and MySQL.
In this post, we will using MySQL as our database and Java as our programming language.
- Download driver class. We need to download driver class, where the driver class can get from http://dev.mysql.com/downloads/connector/j/. Download the latest version of the JDBC driver for MySQL.
- Add .jar file into your program’s classpath. Open eclipse, create a new Java project (eg.
Tutorial
) and then click Next. Select Libraries Tab and click Add External JARs.After browsing the .jar file you just downloaded, click Finish.
- Create package. Right click src, create a new package with name
database
. - Create project under package. Right click the package
database
and create a new project, name it asdatabaseConnection
. - Paste this code in your databaseConnection file.
package database; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseConnection { String driver; String dbName; String connectionURL; String username; String password; public DatabaseConnection() { driver = "com.mysql.jdbc.Driver"; connectionURL = "jdbc:mysql://localhost/"; dbName = "moviedatabase"; username = "root"; password = ""; } public Connection getConnection() throws Exception { Class.forName(driver); Connection connection = DriverManager.getConnection(connectionURL+dbName,username,password); return connection; } public static void main(String[] args) { DatabaseConnection db = new DatabaseConnection(); try { Connection conn = db.getConnection(); System.out.println("Database successfully connected!"); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
- Download wampserver from http://www.wampserver.com/en/. Click the wampserver icon (green color) and click
phpMyAdmin
. - Create a database named
moviedatabase
. Noted that this step is very important. Your database name must be the same as dbName, which was written in databaseConnection.java. - Lastly, run the databaseConnection file in eclipse. If you see Database successfully connected!, Congratulations ! You have successfully connected MySQL database with Java.
Please leave a comment below if you have any questions to ask. Thanks.