, , , sql? , , , .
, , , , ...
, Ive , , ..... ( , PGConnect.java , . SO . java/ .)
, , , , Connection static, , .
, , , .
package DatabaseCodePackage;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class PgConnect {
public static Connection getConnection(String username, String password) throws SQLException
{
return DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", username, password);
}
- ....
SQL JDBC , , , , , -. . http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html . Ive SQL, .
package DatabaseCodePackage;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ReturnResults {
public static void main(String[] args) {
Stirng result = null;
try{
result = selectAllWithEnv("TEST");
} catch (NullPointerException npe){
result = "Connection Failed! Check output console : " + e.getMessage();
e.printStackTrace();
return;
} catch (SQLException e) {
result = "SQL failure! Check output console : " + e.getMessage();
e.printStackTrace();
return;
} finally {
System.out.println(result);
}
}
public static String selectAllWithEnv(String var) throws SQLException, NullPointerException {
String SQL = "select * from mwp.servers where env=? order by server";
Connection connection = null;
StringBuilder sb = new StringBuiler();
try {
connection = PgConnect.getConnection();
PreparedStatement ps = connection.prepareStatement(SQL);
ps.setObject(1, var);
ResuletSet rs = ps.executeQuery();
while (rs.next()) {
String iEnv = rs.getString("env");
String iServer = rs.getString("iserver");
String iLabel = rs.getString("label");
String iTitle = rs.getString("title");
String iLogin = rs.getString("login");
sb.append(iEnv + "\t" + iServer + "\t" + iLabel + "\t" + iTitle + "\t" + iLogin + "\n");
}
} finally {
connection.close();
}
return sb.toString();
}
, con.close() finally. . excetch try, . , , , . , , DBA - , . stmt.close() con.close(), , con.close()