★ JDBC获取
https://opengauss.org/zh/download/
★ 环境信息
✔ 数据库版本:openGauss 5.0.0
✔ 数据库端口:5432
✔ 数据库名称:db_zzt
✔ Java版本:JDK1.8
★ 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();
}
}
}
※ 如果您觉得文章写的还不错, 别忘了在文末给作者点个赞哦 ~