GaussDB 开发篇+Java调用JDBC访问openGauss数据库

★ 数据库信息

✔ 数据库版本:openGauss 5.0.0
✔ 数据库端口:5432
✔ 数据库名称:db_zzt

★ Java代码

package PAC_001;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class C_O {
	public static void main(String[] args) {
		// 创建数据库连接。
		Connection conn = GetConnection("zzt", "PASSWORD");
		// 执行预编译语句,查询数据
		SelectPreparedSQL(conn);
		// 关闭数据库连接。
		try {
			conn.close();
			System.out.println("Disconnect succeed!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static Connection GetConnection(String username, String passwd) {
		String driver = "org.postgresql.Driver";
		String sourceURL = "jdbc:postgresql://1.1.1.9:5432/db_zzt";
		Connection conn = null;
		try {
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		try {
			conn = DriverManager.getConnection(sourceURL, username, passwd);
			System.out.println("Connection succeed!");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return conn;
	};

	public static void SelectPreparedSQL(Connection conn) {
		PreparedStatement pstmt = null;
		try {
			String sql;
			sql = "SELECT empno,ename FROM zzt.emp";
			pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				int id = rs.getInt("empno");
				String name = rs.getString("ename");
				System.out.print("ID: " + id);
				System.out.print(", NAME: " + name);
				System.out.print("\n");
			}
			System.out.println("Select table succeed!");
			rs.close();
			pstmt.close();
		} catch (SQLException e) {
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(数据库+GaussDB,java,gaussdb,数据库,openGauss,Java访问openGauss)