★ 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();
}
}
}
※ 如果您觉得文章写的还不错, 别忘了在文末给作者点个赞哦 ~文章来源:https://www.toymoban.com/news/detail-642782.html
文章来源地址https://www.toymoban.com/news/detail-642782.html
到了这里,关于GaussDB 开发篇+Java调用JDBC访问openGauss数据库的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!