You can use this code in any java application.
Expand|Select|Wrap|Line Numbers
- import java.sql.*;
- public class DBConnect {
- private Connection con;
- private String connstring;
- private PreparedStatement ps;
- private ResultSet rs;
- private String tablename;
- public String getTablename() {
- return tablename;
- }
- public void setTablename(String tablename) {
- this.tablename = tablename;
- }
- public Connection getCon() {
- return con;
- }
- public void setCon(Connection con) {
- this.con = con;
- }
- public String getConnstring() {
- return connstring;
- }
- public void setConnstring(String connstring) {
- this.connstring = connstring;
- }
- public ResultSet getRs() {
- return rs;
- }
- public void setRs(ResultSet rs) {
- this.rs = rs;
- }
- public PreparedStatement getPs() {
- return ps;
- }
- public void setPs(PreparedStatement ps) {
- this.ps = ps;
- }
- public void setDriver() {
- connstring = "org.postgresql.Driver";
- try {
- Class.forName(connstring);
- } catch (ClassNotFoundException ex) {
- System.out.print("Driver cannot be registered");
- }
- }//end of setDriver()
- public void startConnection() throws SQLException {
- con = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/myshop", "postgres", "postgres");
- }//end of startConnection()
- public void setStatement() throws Exception {
- ps = con.prepareStatement("select * from " + tablename, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
- }//end of setStatement()
- public void getQueryResult() throws Exception {
- rs = ps.executeQuery();
- //extractRS();
- }//end of getQueryResult()
- public int getRows() throws Exception {
- int totalrows = 0;
- while (rs.next()) {
- totalrows++;
- }
- rs.beforeFirst();
- return totalrows;
- }//end of getRows
- public int getCols() throws Exception {
- ResultSetMetaData rsmd = rs.getMetaData();
- int cols = rsmd.getColumnCount();
- return cols;
- }//end of getCols()
- public String[][] extractRS() throws Exception {
- String arr[][] = new String[getRows()][getCols()];
- int rows = 0;
- while (rs.next()) {
- for (int i = 0; i < getCols(); i++) {
- arr[rows][i] = rs.getString(i + 1);
- }//end of for loop
- rows++;
- }//end of while loop
- // con.close();
- return arr;
- }//end of extractRS()
- }//end of DBConnect class