使用java写一个对接gaussdb的例子【玩转华为云】
        【摘要】 以下是一个使用Java对接GaussDB的例子:import java.sql.*;public class GaussDBExample {    public static void main(String[] args) {        // JDBC连接信息        String url = "jdbc:postgresql://localhost:5432/mydataba...
    
    
    
    以下是一个使用Java对接GaussDB的例子:
import java.sql.*;
public class GaussDBExample {
    public static void main(String[] args) {
        // JDBC连接信息
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String username = "myusername";
        String password = "mypassword";
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 加载驱动
            Class.forName("org.postgresql.Driver");
            // 创建连接
            conn = DriverManager.getConnection(url, username, password);
            // 创建语句
            stmt = conn.createStatement();
            // 查询语句
            String sql = "SELECT * FROM mytable";
            // 执行查询
            rs = stmt.executeQuery(sql);
            // 处理结果
            while (rs.next()) {
                String col1 = rs.getString("col1");
                int col2 = rs.getInt("col2");
                System.out.println("col1: " + col1 + ", col2: " + col2);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
该示例程序使用JDBC驱动连接到GaussDB数据库,并执行简单的SELECT语句,打印出查询结果。具体使用时,需要将连接信息替换为实际的数据库连接信息,以及编写需要执行的SQL语句。
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
             
           
评论(0)