import java.sql.*;
import java.util.Date;
public class JDBCTest {
private Connection con = null;
private Statement stmt = null;
private PreparedStatement pstmt = null;
public void setDBConnection(String url, String user, String password) {
try {
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
;
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public void printQueryResult(String sql) {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {//USER, EMAIL, COMMENT, DATE
System.out.println("MyUser\t" + "Email\t" + "Comment\t" + "Date");
while (rs.next()) {
String myUser = rs.getString("USER");
String email = rs.getString("EMAIL");
String comment = rs.getString("COMMENT");
System.out.println(myUser + "\t" + email + "\t" + comment + "\t");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testPrep(String updateSql, String col1, String col2, String col3, String col4) {
try {
pstmt = con.prepareStatement(updateSql);
} catch (SQLException e) {
e.printStackTrace();
}
//User, Email, CommentDate, Comment
try {
pstmt.setString(1, col1);
pstmt.setString(2, col2);
pstmt.setDate( 3, java.sql.Date.valueOf(col3) );
pstmt.setString(4, col4);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String dbURL = "jdbc:db2://localhost:50000/sample";
String user = "db2admin";
String password = "******"; //Change to your own login/passwd
String sql = "SELECT * FROM db2admin.comments";
//USER, EMAIL, COMMENT, DATE
//INSERT INTO into db2admin.comments (user,email, commentdate, comment)
//values("Bob", "bob@mail.com", "2019-02-19", "Very comprehensive and well developed book!");
String prepSql = "INSERT INTO db2admin.comments (user, email, commentdate, comment) VALUES (?, ?, ?, ? )";
JDBCTest demo = new JDBCTest();
demo.setDBConnection(dbURL, user, password);
demo.testPrep(prepSql, "Bob", "bob@mail.com", "2019-02-19",
"Very comprehensive and well developed book!" );
demo.printQueryResult(sql);
}
}