JDBC PostgreSQL

上一节
JDBC可以操作多种数据库,而且都是标准化操作。区别仅仅在使用不同的数据库连接驱动程序,及URL连接方式的书写。
//引用SQL包
import java.sql.*;
public class JDBCTest {
/**
* @param args
*/
public static void main(String[] args) {
// 声明资源
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 连接Postgresql数据库,记得先加入JDBC驱动jar包
String driverName = “org.postgresql.Driver”;
Class.forName(driverName);
String url = “jdbc:postgresql://localhost:5432/abc”;
connection = DriverManager.getConnection(url, “abc”, “abc”);
System.out.println(“连接postgresql9.1.5成功!”);
String strSql=null;
statement = null;
resultSet = null;

        // 插入数据操作
        try {
            strSql="INSERT INTO notice( title, content)   VALUES ('这是标题','这是内容')";
            statement=connection.createStatement();
            //执行SQL
            statement.executeUpdate(strSql);
            System.out.println("插入数据成功!"+strSql);
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        }
           
        //查询操作
        try{
            strSql="SELECT content, title   FROM notice";
            statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            //执行SQL
               
            resultSet=statement.executeQuery(strSql);
            if (resultSet.next()){
                System.out.println(resultSet.getString("title")+"___________"+resultSet.getString("content"));
            }
        }catch (SQLException ex2) {
            ex2.printStackTrace();
        }
           
        //删除操作
        try {
            strSql="DELETE FROM notice";
            statement=connection.createStatement();
            //执行SQL
            statement.executeUpdate(strSql);
            System.out.println("删除数据成功!"+strSql);
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        }
           
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 释放资源
        try{
            if (resultSet!=null){
                resultSet.close();
                resultSet=null;
            }
            if (statement!=null){
                statement.close();
                statement=null;
            }
            if (connection!=null){
                connection.close();
                connection=null;
            }
        }catch(SQLException ex){
            System.err.println(ex.getMessage());
        }
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值