在我们编程时有时需要连接数据库,这里是使用Java连接PostgreSQL,下面给出一个连接PostgreSQL的简单代码
import java.sql.*;
public class DBConnect1 {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Connection con;
Statement st;
ResultSet rs;
String url="jdbc:postgresql://localhost:5432/postgres";
String user="postgres";
String password="";//此处输入你的登录密码
Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection(url,user,password);
st=con.createStatement();
rs=st.executeQuery("SELECT 1 AS col_1");
rs.next();
System.out.println(rs.getInt("col_1"));
rs.close();
st.close();
con.close();
}
}
但这时会报错
因为没有导入PostgreSQL的JDBC驱动,也就找不到org.postgresql.Driver
PostgreSQL的JDBC下载地址https://jdbc.postgresql.org/download.html
根据安装的JDK版本选择相应的JDBC版本,
然后在项目下新建一个文件夹
命名为lib->Finsh
将下载好的JDBC拖拽到lib文件夹下
然后Build Path->Configure Build Path...
点击Libraries->Add JARs...
然后选择lib文件夹下的JDBC-->OK
点击Apply或者Apply and Close
此时再次重新编译源文件就会发现以成功连接PostgreSQL了!