在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java连接PostgreSQL数据库

2016-12-20 13:17| 发布者: zhangjf| 查看: 486| 评论: 0

摘要: 代码 import java.sql.DriverManager;import java.sql.Connection;import java.sql.SQLException;import java.sql.ResultSet;import java.sql.Statement;public class PG{ public static void main(String args) ...
[Java]代码      
  1. import java.sql.DriverManager;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. public class PG{
  7.         public static void main(String []args){
  8.                 System.out.println("PostgreSQL JDBC...");
  9.                 try {
  10.                         Class.forName("org.postgresql.Driver");
  11.                 }catch (ClassNotFoundException e){
  12.                         System.out.println("could not find postgreSQL JDBC Driver");
  13.                         e.printStackTrace();
  14.                         return;
  15.                 }
  16.                 Connection connection = null;
  17.                 try {
  18.                         connection = DriverManager.getConnection(
  19.                                         "jdbc:postgresql://localhost:5432/postgres",
  20.                                         "postgres",
  21.                                         "");
  22.                 }catch (SQLException e){
  23.                         System.out.println("Connection Failed");
  24.                         e.printStackTrace();
  25.                         return;
  26.                 }
  27.                 if (connection != null){
  28.                         System.out.println("connect db successful!");
  29.                 }else {
  30.                         System.out.println("Failed to make conn!");
  31.                 }
  32.                 try {
  33.                         Statement  stmt = connection.createStatement();
  34.                         ResultSet rs = stmt.executeQuery("SELECT 1 AS A");
  35.                         if(rs!=null){
  36.                                 rs.next();
  37.                                 System.out.println(rs.getInt("a"));
  38.                         }else {
  39.                                 System.out.println("null");
  40.                         }
  41.                         rs.close();
  42.                         stmt.close();
  43.                         connection.close();
  44.                 }catch (Exception exp){
  45.                         exp.printStackTrace();
  46.                 }
  47.         }
  48. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 17:11

Copyright 2015-2025 djqfx

返回顶部