Postgresql驱动的jar包链接:https://jdbc.postgresql.org/download.html.
Postgresql数据库以及图形管理软件
链接:https://pan.baidu.com/s/1cJpGO_d6iUpNjMbZzspLcQ 提取码:8xfk
Java链接Postgresql数据库实例:
public static void main(String[] args)throws Exception {
Class.forName("org.postgresql.Driver");
Connection conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/SchoolJiFang","postgres","123456");
System.out.println("数据库查询成功");
}
查询数据
//查询数据
public static void queryData(Connection conn)
{
try {
//Postgresql数据库和mysql数据库不同,是区分大小写的。
// select ?,?,? from userInfromation; 这种语法格式是错误的:不能把字段的关键字设置为?,应该对sql语句的参数设置值。
String sql="SELECT id, name, password, power FROM \"UserInformation\" where id=?" ;
PreparedStatement stat= conn.prepareStatement(sql);
stat.setInt(1, 3); //id为Int类型,所以为id赋值使用setInt();
ResultSet res= stat.executeQuery();
while (res.next()) {
int id= res.getInt(1);
String name=res.getString("name");
System.out.println("id:"+id+",name:"+name);
}
res.close();
stat.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
}
更新数据:
//更新数据
public static void updateData(Connection conn)
{
try {
String sql="Update \"UserInformation\" set name=? where id=?";
PreparedStatement stat =conn.prepareStatement(sql);
stat.setString(1, "hys");
stat.setInt(2, 1);
int lines= stat.executeUpdate();
System.out.println("lines:"+lines+",更新数据成功");
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
}
插入数据:
public static void insertData(Connection conn)
{
try {
String sql="insert into \"UserInformation\" (id,name,password,power) values(?,?,?,?)";
PreparedStatement stat= conn.prepareStatement(sql);
stat.setInt(1, 4);
stat.setString(2, "wanger");
stat.setString(3, "wanger");
stat.setInt(4, 4);
int lines= stat.executeUpdate();
System.out.println("lines:"+lines+"数据插入成功");
stat.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
}
删除数据
//删除数据
public static void deleteData(Connection conn)
{
try {
String sql="delete from \"UserInformation\" where id=?";
PreparedStatement stat= conn.prepareStatement(sql);
stat.setInt(1, 4);
int lines= stat.executeUpdate();
System.out.println("lines:"+lines+"删除数据成功");
stat.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
}