JAVA – Connect to MYSQL

In this tutorial provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query or statements and display the results.

For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity.

In this example we are using MySql as the database. So we need to know following information for the mysql database:
  1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
  2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/student where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and student is the database name. We may use any database, in such case, you need to replace the student with your database name.
  3. Username: The default username for the mysql database is root.
  4. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password.
Let's take one example.

Step 1: search for the XAMPP.
Search for XAMPP
1.1 Search for XAMMP
Step 2: open any web browser and write localhost/phpmyadmin.
phpmyadmin
1.2 phpmyadmin

Step 3: Create Database student and table student which have two column like rollno and name.
Step 4: Now open NetBeans and create new project database.
Step 5: In this project create one java class file.
Java - NetBeans
1.3 NetBeans

Step 6: download JDBC driver from 

Copy jar file and paste in library in your project.

Step 6: DBconnect.java

import java.sql.*;
public class DBconnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBconnect(){
try {
//class.forname("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
st=con.createStatement();
}catch(Exception ex){
     System.out.println("Erro : "+ex);
}
}
public void getData() {
try {
String query="select * from student";
rs=st.executeQuery(query);
     System.out.println("Records from Database");
while(rs.next()) {
String Rollno=rs.getString("Rollno");
String Name=rs.getString("Name");
     System.out.println("Rollno "+Rollno+" "+Name);
}
}catch(Exception ex){
     System.out.println(ex);
}
}
}

Step 7: In main method create object of DBconnect and call getData method.

DBconnect connect=new DBconnect();
connect.getData();


Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon