关于postgreSQL的CRUD操作的简单类:
import java.sql.*;
public class MyDB
{
public Connection conn=null;
public Statement stmt=null;
public ResultSet rs=null;
public PreparedStatement pstmt;
static String dbDriver="org.postgresql.Driver";
static String dbUrl="jdbc:postgresql://127.0.0.1:5432/postgres";
static String dbUser="postgres";
static String dbPwd="xxxx";
int result1;
//打开数据库连接
public static Connection getConnection()
{
Connection conn=null;
try
{
Class.forName(dbDriver);
conn=DriverManager.getConnection(dbUrl,dbUser,dbPwd);
}
catch(Exception e)
{
e.printStackTrace();
}
if (conn == null)
{
System.err.println("警告:数据库连接失败!");
}
return conn;
}
//添加数据
public int doInsert(String no,String name)
{
String name1=name;
try
{
conn=MyDB.getConnection();
String str1="insert into tongxunlu values(?,?)";
pstmt=conn.prepareStatement(str1);
pstmt.setString(1,no);
pstmt.setString(2,name);
result1=pstmt.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result1;
}
//读取结果集
public ResultSet doQuery(String no2)
{
String no=no2;
try
{
conn=MyDB.getConnection();
stmt=conn.createStatement();
String sql2="select * from tongxunlu where no='"+no2+"'";
rs=stmt.executeQuery(sql2);
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
//更新数据
public int doUpdate(String no1,String name2)
{
int result = 0;
try
{
conn=MyDB.getConnection();
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql3="update tongxunlu set name='"+name2+"' where no='"+no1+"'";
result=stmt.executeUpdate(sql3);
}
catch(SQLException e)
{
}
return result;
}
//删除操作
public int doDrop(String no1)
{
int result=0;
try
{
conn=MyDB.getConnection();
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql4="delete from tongxunlu where no='"+no1+"'";
result=stmt.executeUpdate(sql4);
}
catch(SQLException e)
{
result=0;
}
return result;
}
//关闭数据库连接
public void closeConnection()
{
try
{
if (rs!=null)
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if (stmt!=null)
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if (conn!=null)
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
对CRUD操作的测试
import java.sql.*;
public class TestCrud {
static String name1;
static String no1;
public static void main(String[] args) throws SQLException {
MyDB md=new MyDB();
Connection con=md.getConnection();
name1="小明";
no1="01";
int resu=md.doInsert(no1,name1);
if(resu==1){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}
String name2="小红";
/*
String no2="01";
ResultSet rs=md.doQuery(no2);
while(rs.next()){
System.out.println("学号:"+rs.getString("no")+"姓名:"+rs.getString("name"));
}
*/
/*
int resu2=md.doUpdate(no1, name2);
if(resu2==1){
System.out.println("修改成功!");
}else{
System.out.println("修改失败!");
}
int resu3=md.doDrop(no1);
if(resu3==1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
*/
}
}