📄 jdbcproductdao.java
字号:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JdbcProductDao implements ProductDao {
private static DataSource ds;
static{
try {
Context context=new InitialContext();
ds=(DataSource)context.lookup("java:comp/env/jdbc/derby");
} catch (NamingException e) {
e.printStackTrace();
}
}
public void deleteById(int id) {
Connection con=null;
PreparedStatement ps=null;
try {
con=ds.getConnection();
String sql="delete from product where id=?";
ps=con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(null,ps,con);
}
}
public void newProduct(int id, String name) {
Connection con=null;
PreparedStatement ps=null;
try {
con=ds.getConnection();
String sql="insert into product values(?,?)";
ps=con.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(null,ps,con);
}
}
public Set<Product> findAll() {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=ds.getConnection();
String sql="select * from product order by id";
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
Set<Product> set=new HashSet<Product>();
while(rs.next()){
Product p=new Product();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
set.add(p);
}
return set;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally{
close(null,ps,con);
}
}
private void close(ResultSet rs,Statement st,Connection con){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(st!=null)
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -