To run the JDBC, you should follow these steps:
1. Download Java MySQL Connector ‘mysql-connector-java-5.1.34-bin.jar’ and keep it
on
the desktop
2. Create a Java project in Eclipse IDE
Open Eclipse IDE. Create a new Java Project and name it as “mydbproj”.
3. Configure JDBC driver in Eclipse IDE
You need to add the downloaded Java MySQL Connector JAR in
client project’s classpath . To do this,right click on your Java Project
(mydbproj) -> Properties -> Buildpath -> Libraries -> Add External
JAR and select “mysql-connector-java-5.1.34-bin.jar” JAR file.
4. Set up a simple database program
import java.sql.*;
public class JdbcExample {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "");
if (!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (con != null)
con.close();
} catch(SQLException e) {}
}
}
}
5. Run the program ->click on Java file -> RunAs-> Java Application. You will get the
following output.
Successfully connected to MySQL server...
2. Program to display the contents of mysql table
import java.sql.*;
public class mysql_demo{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
String f1,f2;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "Select * FROM stud";
System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
f1 = rs.getString(1);
f2 = rs.getString(2);
System.out.println(f1+" "+f2);
} //end while
conn.close();
System.out.println("Disconnected from database");
} //end try
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
3. Program to insert data into the table and display the contents.
import java.sql.*;
import java.io.*;
class JDBC_prepared_ins_ex{
public static void main(String args[])throws Exception{
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
String myusn,myname;
PreparedStatement ps=conn.prepareStatement("insert into stud
values(?,?)");
Statement stmt = conn.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
//int id=Integer.parseInt(br.readLine());
//float salary=Float.parseFloat(br.readLine());
//ps.setFloat(2, salary);
System.out.println("enter usn:");
myusn=br.readLine();
System.out.println("enter name:");
myname=br.readLine();
ps.setString(1,myusn);
ps.setString(2,myname);
int i=ps.executeUpdate();
System.out.println(i+" records added");
System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
String sql = "SELECT * from stud";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("The records are :");
while (rs.next())
{
myusn = rs.getString(1);
myname=rs.getString(2);
System.out.println(rs.getRow()+"-"+myusn+" "+myname);
} //end while
conn.close();
}}
4. Example for Scrollable Result
import java.sql.*;
public class JDBC_resultset{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
String uname,mypass;
try {
Class.forName(driver).newInstance();
conn =
DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
Statement stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_RE
AD_ONLY);
String sql;
sql = "SELECT username,password from admin";
ResultSet rs = stmt.executeQuery(sql);
// Move cursor to the last row.
System.out.println("Moving cursor to the last...");
rs.last();
System.out.println("Displaying record...");
//Retrieve by column name
uname = rs.getString("username");
mypass = rs.getString("password");
//Display values
System.out.print("Username: " + uname);
System.out.println(", Password: " + mypass);
// Move cursor to the first row.
System.out.println("Moving cursor to the first row...");
rs.first();
//Retrieve by column name
uname = rs.getString("username");
mypass = rs.getString("password");
//Display values
System.out.print("Username: " + uname);
System.out.println(", Password: " + mypass);
System.out.println("Moving cursor to the next
row...");
rs.next();
//Retrieve by column name
uname = rs.getString("username");
mypass = rs.getString("password");
//Display values
System.out.print("Username: " + uname);
System.out.println(", Password: " + mypass);
conn.close();
System.out.println("Disconnected from database");
} //end try
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}