Database Connection and SQL Query

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtils {

public static void main(String[] args) {
	try {
		executeQuery(”select * from persons”);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

public static void executeQuery(String sql) throws Exception {
	Connection conn = null;
	Statement stmt = null;
	ResultSet rs = null;
	try {
		conn = getConnection();
		stmt = conn.createStatement();
		rs = stmt.executeQuery(sql);
		while (rs.next()) {
			String oid = (String) rs.getObject(”oid”);
			System.out.println(”oid = ” + oid);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		rs.close();
		stmt.close();
		conn.close();
	}
}

public static Connection getConnection() throws Exception {
	Connection conn = null;
	String driverName = “org.postgresql.Driver”;
	String databaseUrl = “jdbc:postgresql://mymachine/mydatabase”;
	String user = “user”;
	String pwd = “password”;
	Driver driver = (Driver) Class.forName(driverName).newInstance();
	DriverManager.registerDriver(driver);
	conn = DriverManager.getConnection(databaseUrl, user, pwd);
	return conn;
}	

}

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Similar Posts

Comments are closed.