从https://jdbc.postgresql.org/download.html下载最新版本的postgresql-(VERSION).jdbc.jar驱动包
。
Java连接到PostgreSQL数据库:
简单的操作查询和添加,其余忽略!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Testsql {
public static void main(String[] args) throws Exception {
add();
show();
}
/**
* 添加
* @throws ClassNotFoundException
* @throws SQLException
*/
private static void add() throws ClassNotFoundException, SQLException {
// 加载驱动
Class.forName("org.postgresql.Driver");
// 获得连接对象: 注意:mydb是数据库;postgres:用户名; 123456:密码
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb", "postgres", "123456");
// INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)VALUES ( 'David', 27, 'Texas', 85000.00 );
String sql="insert into company(name,age,address,salary) values(?,?,?,?)";
// 预编译对象
PreparedStatement ps = con.prepareStatement(sql);
//设置参数的值
ps.setString(1, "David");
ps.setInt(2, 27);
ps.setString(3, "Texas");
ps.setDouble(4, 85000.00);
ps.execute();
// 关闭连接
ps.close();
con.close();
}
/**
* 查询数据
* @throws ClassNotFoundException
* @throws SQLException
*/
private static void show() throws ClassNotFoundException, SQLException {
// 加载驱动
Class.forName("org.postgresql.Driver");
// 获得连接对象: 注意:mydb是数据库;postgres:用户名; 123456:密码
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb", "postgres", "123456");
//System.out.println(con);
// 预编译对象
PreparedStatement ps = con.prepareStatement("select * from company");
// 返回结果集
ResultSet rs = ps.executeQuery();
// 遍历数据
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getInt(3) + "\t" + rs.getString(4)+ "\t" + rs.getString(5));
}
// 关闭连接
rs.close();
ps.close();
con.close();
}
}
效果: