Java连接PostgreSQL数据库详解编程语言

[Java]代码    

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(); 
		} 
	} 
} 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10345.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论