<分区>
第一次在这里提问,如有不妥请见谅
我像这样连接到 java 中的 postgresql:
一个 Maven xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SQL_Database</groupId>
<artifactId>SQL_Database</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.1</version>
</dependency>
</dependencies>
</project>
3 个类:Connect.java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connect {
private Connection conn;
public Connect(){
}
public void setConnection(String database, String user, String password){
String format = String.format("jdbc:postgresql://localhost/%s", database);
Properties props = new Properties();
props.put("user", user);
props.put("password", password);
try {
this.conn = DriverManager.getConnection(format, props);
this.conn.setAutoCommit(true);
} catch (SQLException e){
System.out.println(e.getMessage());
}
}
public Connection getConnection(){
return this.conn;
}
public void closeConnection() {
try {
this.conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
SQL.java:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
class Sql {
private Connection conn;
private ResultSet results;
public Sql(Connection conn) {
this.conn = conn;
}
public void update(String query) {
try {
this.conn.prepareStatement(query).executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void select(String query) {
try {
this.results = this.conn.prepareStatement(query).executeQuery();
getResults();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
和 Main.java:
import java.sql.Connection;
public class Main {
public static void main(String args[]){
Connect c = new Connect();
c.setConnection("foo", "foo", "foo");
Connection conn = c.getConnection();
Sql sql = new Sql(conn);
String query = <Some SQL statement>;
sql.update(query);
sql.select(<Some SQL statement>);
c.closeConnection();
}
}
这非常有效,我可以创建表格,从这些表格中选择内容等。
但是,我想在另一个项目中有这个连接,所以我在那个项目中重新创建了 Connect 和 Sql 类,并将 Main.java 中的语句添加到另一个项目中的主类中。
我可以执行 Connect c = new Connect();
并且可以正常工作,但是当我尝试执行 c.setConnection("foo", "foo", "foo") ;
,它不起作用,Java 不识别c
对象或其他东西。
sql
也是一样。
我不明白为什么它在一个项目中有效,但如果我在另一个项目中做完全相同的事情,它就不起作用。
这是我项目中不起作用的代码:
public class Main extends Application {
Connect c = new Connect();
c.setConnection("foo", "foo", "foo");
Connection conn = c.getConnection();
Sql sql = new Sql(conn);
-- Some other code that works perfectly without the above--
}
附言。对不起,代码炸弹。