Create a Database to query
First, set up a MySQL database. For the purposes of this demonstration I set up a simple database called bluecoat with one table: student. The table has four columns of type varchar: Forename, Surname, Gender and Form.
Update: Follow this link to watch a YouTube demonstration of this lesson
Add mysql-connector JAR
You will need to download the mysql-connector JAR and add it to your classpath. Consult your IDE’s documentation on how to do this.
You can find the JAR here: https://dev.mysql.com/downloads/connector/j/
If you’re using Netbeans, right click on the Libraries folder and choose Add JAR/Folder
The JAR is installed by default in the ext folder on windows:
Quick Start
The following code will connect to a database called bluecoat running on a mysql server on port 3306 of localhost. I used XAMPP to write this tutorial: by default the username of the database was root, the password was left blank.
try { //Load mysql jdbc Driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to Database Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", ""); } catch (Exception ex) { System.err.println(ex); }
Run the code. If it doesn’t throw an exception, you’re successfully connected!