Connecting to MySQL Database using Thin Driver
To connect a Java application with MySQL database using Thin Driver. You need to follow the following steps
- Load Driver Class: The Driver Class for MySQL database is com.mysql.jdbc.Driver and
Class.forName("com.mysql.jdbc.Driver")
method is used to load the driver class for MySQL database.
- Create Connection: For creating a connection you will need a Connection URL. The Connection URL for MySQL is
You will also require Username and Password of your MySQL Database Server for creating connection.
- Loading jar file: To connect your java application with MySQL, you will also need to load
mysql-connector.jar
file. This file can be loaded into 2 ways.
- Copy the jar file into
C:\Program Files\Java\jre7\lib\ext
folder.
or,
- Set it into classpath. For more detail see how to set classpath
Time for an Example!
Let's see programs for performing simple operations like create, insert and select on database tables.
Create a table in MySQL Database
Use the below SQL command to create a table Student into mysql database. This table has two columns: sid and name.
create table Student(sid int(10),name varchar(20));
Insert some record into the table
After creating the table now insert two records into table using the below sql command. Here we are inserting adam and abhi named two rows.
insert into Student values(102,'adam');
insert into Student values(103,'abhi');
Example: Accessing record
In the above example, we inserted two records using SQL command. Now we are fetching those records using JDBC Java application.
import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver");
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/test","username","password");
Statement s = con.createStatement(); //creating statement
ResultSet rs = s.executeQuery("select * from Student"); //executing statement
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
con.close(); //closing connection
}catch(Exception e){
e.printStackTrace();
}
}
}
102 adam 103 abhi
Example: Inserting Record
We can insert data into table using Java application. Here we are using Prepared statement and parameterized query to execute SQL query. The executeUpdate() method is used to execute the insert query. See the below example.
import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver");
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/test","username","password");
PreparedStatement pst=con.prepareStatement("insert into Student values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();
con.close(); //closing connection
}catch(Exception e){
e.printStackTrace();
}
}
}