Java 使用jdbc 连接PostgreSQL 数据库

必须添加 rs.next(); 否则报错

org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.

代码实例

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){
		System.out.println("PostgreSQL JDBC...");
		try {
			Class.forName("org.postgresql.Driver");
		}catch (ClassNotFoundException e){
			System.out.println("could not find postgreSQL JDBC Driver");
			e.printStackTrace();
			return;
		}
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost:5432/postgres", 
					"postgres",
					"");
		}catch (SQLException e){
			System.out.println("Connection Failed");
			e.printStackTrace();
			return;
		}

		if (connection != null){
			System.out.println("connect db successful!");
		}else {
			System.out.println("Failed to make conn!");
		}
		try {
			Statement  stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT 1 AS A");
			if(rs!=null){
				rs.next();  // 必须添加
				System.out.println(rs.getInt("a"));
			}else {
				System.out.println("null");
			}
			rs.close();
			stmt.close();
			connection.close();
		}catch (Exception exp){
			exp.printStackTrace();
		}
	}
}

转载于:https://my.oschina.net/innovation/blog/631476

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值