我在博客里有一篇《Java使用jdbc连接数据库》,连接成功以后就需要对数据库进行操作,今天这篇博文主要介绍我在Java中经常用到的数据库操作,只挑最常用的代码示例。
一.查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public String getC_name(int c_id) { // TODO Auto-generated method stub String c_name=""; Connection conn = DBUtil.getConnectDb(); String sql="select * from customer where c_id=?"; try { PreparedStatement stm = conn.prepareStatement(sql); stm.setInt(1, c_id); ResultSet rs = stm.executeQuery(); if(rs.next()) { c_name = rs.getString("c_name"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return c_name; } |
二.修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public void is_loginInfo(int m_id,int is_login) { Connection conn = DBUtil.getConnectDb(); String sql="update manager set is_login=? where m_id=?"; PreparedStatement stm = null; try { stm = (PreparedStatement) conn.prepareStatement(sql); is_login=(is_login==1?0:1); // System.out.println(is_login); stm.setInt(1, is_login); stm.setInt(2, m_id); stm.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } |
三.插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public int insertProduct(ProductBean item) { // TODO Auto-generated method stub Connection conn = DBUtil.getConnectDb(); String sql="insert into product(p_name,p_money,p_totalnum,p_desc,back_money,p_id) values(?,?,?,?,?,?)"; int rs = 0; try { PreparedStatement stm = conn.prepareStatement(sql); stm.setString(1, item.getP_name()); stm.setInt(2, item.getP_money()); stm.setInt(3, item.getP_totalnum()); stm.setString(4, item.getP_desc()); stm.setInt(5, item.getBack_money()); stm.setInt(6, item.getP_id()); rs = stm.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rs; } |
四.删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public static void main(String[] args) { Connection conn = DBUutil.getConnectDb(); String sql="delete from user where name='scs'"; PreparedStatement stm = null; ResultSet rs = null; int rss=0; try { stm = conn.prepareStatement(sql); rss=stm.executeUpdate(sql); System.out.println(rss); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } finally { DBUutil.CloseDB(rs,stm,conn); } } |