我有这样一个程序连接到数据库,然后发送查询并得到答案。当我在主类中进行连接和查询时,一切都很好,但是当我尝试创建3个不同的类时,我的程序不起作用。如何从查询中调用connect函数,然后从main调用查询函数?
public class App {
public static void connect() throws IOException {
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
public static void query() {
Connection c = connect(); // call function - error
Statement stmt = c.createStatement();
stmt = c.createStatement();
String query = "Select count(distinct country) sum from customers";
ResultSet rs = stmt.executeQuery(query);
query = "SELECT * from country";
rs = stmt.executeQuery(query);
while (rs.next()) {
String country = rs.getString("country");
String netamount = rs.getString("netamount");
System.out.println(country + " " + netamount);
System.out.println();
}
rs.close();
stmt.close();
c.close();
}
public static void main(String[] args) {
query(); // call function
}
答案 0 :(得分:0)
所以你的函数需要返回一个Connection
尝试重写这个
public static Connection connect() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("login.txt"));
dbName = br.readLine();
userName = br.readLine();
password = br.readLine();
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
return c;
}
然后您的查询功能将按预期工作,尤其是行
Connection c = connect();