首先抱歉标题的名称,但我不知道怎么放另一个,因为英语不是我的母语.
我有以下方法连接到数据库:
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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要做的是包括PgConnect
下面代码中的方法.基本上我需要这个,因为我有很多类型的SQL对数据库的调用,并且这种方式的更改很容易维护,因为凭证/主机只能在一个文件上.
我相信改变应该是我发表评论的地方
// i want to change this, for using the method on the first file.
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我.
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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何在Perl上执行此操作,但我没有任何Java实践.
隐藏凭据的一种方法是创建connect
一个返回 的静态函数Connection
,如下所示:
public class PgConnect {
public static Connection connect() throws SQLException {
try {
Connection res = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
if (res != null) {
System.out.println("Connection working");
} else {
System.out.println("Failed to make connection!");
}
return res;
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
}
然后你可以像这样使用它:
try {
connection = PgConnect.connect();
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1957 次 |
最近记录: |