上一节
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());
}
}
}
}