Java Database Connectivity With MySQL
Java Database Connectivity With MySQL
To connect Java application with the MySQL database, we need to follow 5 following
steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
download this example
The above example will fetch all the records of emp table.
2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent