使用jdbc连接本地postgreSQL的一个例子

package postgresql;

import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

public class PostgreSQLJDBC {

	private Connection connection = null;

	@SuppressWarnings("unused")
	private void select() {
		try {
			int index = 0;
			Class.forName("org.postgresql.Driver");
			connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost:9812/zproduct", "postgres", "Saptest1");
			Statement stmt = connection.createStatement();
			String query = "SELECT * FROM public.comm_product;";
			ResultSet rs = stmt.executeQuery(query);
	         while ( rs.next() ) {
	        	System.out.println("Row index: " + index++);
	            
	        	String  client = rs.getString("client");
	            System.out.println("Client: " + client);
	            
	            String  guid = rs.getString("product_guid");
	            System.out.println("Product guid: " + guid);
	            
	            Timestamp validFrom = rs.getTimestamp("valid_from");
	            System.out.println("Valid from: " + validFrom);
	         }
	         rs.close();
	         stmt.close();
	         connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public static void main(String args[]) {
		PostgreSQLJDBC jdbcTest = new PostgreSQLJDBC();
		//jdbcTest.select();
		jdbcTest.clobTest();
	}
	
	@SuppressWarnings("unused")
	private void clobTest(){
		
		String description = null;
	    Clob myClob = null;
	    PreparedStatement pstmt = null;

	    try {
	    	connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost:9812/zproduct", "postgres", "Saptest1");
	        String sql =
	            "select text " +
	            "from public.ztest2 " +
	            "where key1 = ?";

	        pstmt = this.connection.prepareStatement(sql);
	        pstmt.setString(1, "1");
	        ResultSet rs = pstmt.executeQuery();

	        if (rs.next()) {
	        	System.out.println(rs.getString(1));
	            //myClob = rs.getClob(1);
	            //System.out.println("Length of retrieved Clob: " +
	            //    myClob.length());
	        }
	        // description = myClob.getSubString(1, 10);
	    } catch (SQLException sqlex) {
	        sqlex.printStackTrace();
	    } catch (Exception ex) {
	        System.out.println("Unexpected exception: " + ex.toString());
	    } finally {
	        if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
	    }
	    // System.out.println("Description: " + description);
	}
}
展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值