首先很抱歉标题的名称,但我不知道如何放置另一个,因为英语不是我的母语。
我有以下方法连接到数据库:
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!");
}
}
}
我需要做的是PgConnect
在下面的代码中包含方法。基本上我需要这个,因为我有多种类型的 SQL 对数据库的调用,并且将其更改为这种方式将很容易维护,因为凭据/主机将仅在一个文件上。
我相信改变应该是我有评论的地方
// i want to change this, for using the method on the first file.
如果我错了,请纠正我。
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!");
}
}
}
我知道如何在 Perl 上做到这一点,但我没有任何 Java 实践。