Sample code to demonstrate MYSQL JDBC connectivity in Java
Download mysql-connector-java-5.0.7.jar and add to your build path to run the code.
Setup the project as show in the image below.
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.ResultSet;
public class TestConnection {
public static void main(String[] argv) {
System.out.println("******** MySQL JDBC Connection ********");
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC Driver Loaded");
Connection connection = null;
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
Statement stmt = connection.createStatement();
rs= (ResultSet) stmt.executeQuery("select * from student");
while (rs.next()) {
System.out.println(rs.getInt(1) + "==" +rs.getString(2) + "==" +rs.getString(3));
} //end while
connection.close();
}
catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not loaded");
e.printStackTrace();
return;
}
catch (SQLException e)
{
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
}
}
Output as shown in below Image
Setup the project as show in the image below.
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.ResultSet;
public class TestConnection {
public static void main(String[] argv) {
System.out.println("******** MySQL JDBC Connection ********");
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC Driver Loaded");
Connection connection = null;
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
Statement stmt = connection.createStatement();
rs= (ResultSet) stmt.executeQuery("select * from student");
while (rs.next()) {
System.out.println(rs.getInt(1) + "==" +rs.getString(2) + "==" +rs.getString(3));
} //end while
connection.close();
}
catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not loaded");
e.printStackTrace();
return;
}
catch (SQLException e)
{
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
}
}
Comments
Post a Comment