我的java编程代码中的dao包老是出现问题,谁可以给我一写个连接数据库的实现增,删,改,查的完整代码。谢谢

2024-11-27 09:58:27
推荐回答(2个)
回答1:

回答2:

链接数据库的 类
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class BaseDao {
private final static String DRIVER="oracle.jdbc.driver.OracleDriver";
private final static String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
private final static String USER="system";
private final static String PASSWORD="accp";
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
Connection con=null;
try {
con=DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public void closeall(Connection con,Statement stat,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

查询语句
public int selectuser(String users,String password){
Connection con=getConnection();
PreparedStatement stat=null;
int count=0;
String sql="select * from USERS where username=? and password=?";
try {
stat=con.prepareStatement(sql);
stat.setString(1,users);
stat.setString(2, password);
count=stat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
增加数据语句
public int adduser(String users,String password){
Connection con=getConnection();
PreparedStatement stat=null;
int count=0;
String sql="insert into users values (SHOPIDADD.NEXTVAL,?,?)";
try {
stat=con.prepareStatement(sql);
stat.setString(1,users);
stat.setString(2, password);
count=stat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
删除语句
public int deletegoods(int id){
Connection con=getConnection();
PreparedStatement stat=null;
int count=0;
String sql="delete from SHOP where id=?";
try {
stat=con.prepareStatement(sql);
stat.setInt(1,id);
count=stat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
你可以参考下 记得采纳哦 呵呵