Prima di tutto mi dispiace per il nome del titolo, ma non so come inserirne un altro dato che l'inglese non è la mia lingua madre.Connessione JDBC utilizzando file diversi
Ho il seguente metodo per connettersi a un database:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class PgConnect {
public void connect() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("Connection working");
} else {
System.out.println("Failed to make connection!");
}
}
}
E quello che devo fare è includere il metodo dal PgConnect
nel seguente codice. Fondamentalmente ho bisogno di questo perché ho molti tipi di chiamate SQL al database, e cambiarlo in quel modo sarebbe facile da mantenere, dal momento che le credenziali/host sarebbero su un solo file.
Credo che il cambiamento dovrebbe essere dove ho il commento
// i want to change this, for using the method on the first file.
favore correggetemi se sbaglio.
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) {
Connection connection = null;
try {
// i want to change this, for using the method on the first file.
connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
String result = null;
String selectString = "select * from mwp.servers where env='TEST' order by server";
//result ="iServer\tLabel\n";
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(selectString);
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");
result=iEnv+"\t"+ iServer+"\t"+iLabel+"\t"+iTitle+"\t"+iLogin;
System.out.println(result);
}
stmt.close();
connection.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
} else {
System.out.println("Failed to make connection!");
}
}
}
So come farlo su Perl, ma non ho alcuna pratica in Java.
Questa soluzione ha funzionato come previsto. Ho fatto l'esatto suggerimento che hai dato e ora sono in grado per arrivare. Grazie. –