欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用JDBC连接postgresql数据库示例

程序员文章站 2024-02-22 21:52:28
本文实例讲述了java使用jdbc连接postgresql数据库。分享给大家供大家参考,具体如下: package tool; import java.sql....

本文实例讲述了java使用jdbc连接postgresql数据库。分享给大家供大家参考,具体如下:

package tool;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
public class psqlconnectiontool {
 private string url = "jdbc:postgresql://xxx.xxx.xxx.xxx:5432/testdb";
 private string username = "postgres";
 private string password = "postgres";
 private connection connection = null;
 public connection getconn() {
  try {
   class.forname("org.postgresql.driver").newinstance();
   connection = drivermanager.getconnection(url, username, password);
  } catch (instantiationexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (illegalaccessexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (classnotfoundexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }catch (sqlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  return connection;
 }
 public resultset query(connection conn, string sql) {
  preparedstatement pstatement = null;
  resultset rs = null;
  try {
   pstatement = conn.preparestatement(sql);
   rs = pstatement.executequery();
  } catch (sqlexception e) {
   e.printstacktrace();
  }
  return rs;
 }
 public boolean queryupdate(connection conn, string sql) {
  preparedstatement pstatement = null;
  int rs = 0;
  try {
   pstatement = conn.preparestatement(sql);
   rs = pstatement.executeupdate();
  } catch (sqlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  if (rs > 0) {
   return true;
  }
  return false;
 }
 public static void main(string[] args) throws sqlexception {
  psqlconnectiontool pgtool = new psqlconnectiontool();
  connection myconn = pgtool.getconn();
  pgtool.queryupdate(myconn, "insert into test values (1,'smoon','man')");
  resultset rs = pgtool.query(myconn, "select * from test");
  while(rs.next()){
   int id = rs.getint("id");
   string name = rs.getstring("name");
   string gender = rs.getstring("gender");
   system.out.println("id:"+id+" 姓名:"+name+" 性别:"+gender);
   myconn.close();
  }
 }
}

更多关于java相关内容感兴趣的读者可查看本站专题:《java使用jdbc操作数据库技巧总结》、《java+mysql数据库程序设计总结》、《java数据结构与算法教程》、《java文件与目录操作技巧汇总》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。