/*-- Example of Insert Data using Prepared Statement --*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class DBInsert{
public static void main(String ar[]) throws SQLException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sender="992003002";
String receiver="Aman Kumar";
String message="Hi testing msg";
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","public");
if(con==null){
System.out.println("DataBase Connection Error....");
System.exit(0);
}
else{
System.out.println("DataBase Connected. ");
}
String strQry="Insert into table1(sender,receiver,message)values(?,?,?)";
ps = con.prepareStatement(strQry);
System.out.println("Ready for Insert...");
ps.setString(1,sender);
ps.setString(2,receiver);
ps.setString(3,message);
ps.executeUpdate();
System.out.println("inserted data in DB...");
ps.close();
con.close();
}
catch (SQLException e){
System.out.println(e);
}
catch (ClassNotFoundException e){
System.out.println(e);
}
}
}
/*-- Example of Select (Get) Data using Prepared Statement --*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBGet {
public static void main(String args[]) throws SQLException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","public");
if(con==null){
System.out.println("DataBase Connection Error....");
System.exit(0);
}
else{
System.out.println("DataBase Connected. \n");
}
ps=con.prepareStatement("SELECT sender,receiver, message FROM table1");
ResultSet rs1 = ps.executeQuery();
while (rs1.next()){
String sender = rs1.getString(1);
String receiver = rs1.getString(2);
String message = rs1.getString(3);
System.out.println(sender + "\t " + receiver + "\t" + message);
}
}
catch (SQLException e){
System.out.println(e);
}
catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}
No comments:
Post a Comment