java mysql 插入带参数数据_怎么用java操作数据库实现(带参数)的增删改查?求具体实例!一定要带参数的哦!...

import java.sql.*;

/**课题:封装数据库的增删改查的工具类的实现。

*

* 假设相关数据库的表结构如下:

* 表名:user

* 列名及属性:id(int 自增),name(varchar(20)),tele(char(12)),birthday(date)

* @author shy2850

*/

public class UserDAO {

Connection conn;

public UserDAO(Connection conn) {

this.conn = conn;

}

public int save(User user) throws SQLException {

String sql = "insert into user values(0,?,?,?)";

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setString(1, user.getName());

pstmt.setString(2, user.getTele());

pstmt.setDate(3, user.getBirthday());

int n = pstmt.executeUpdate();

pstmt.close();

return n;

}

public int delete(User user) throws SQLException{

String sql = "delete from user where id = "+user.getId();

Statement stmt = conn.createStatement();

int n = stmt.executeUpdate(sql);

stmt.close();

return n;

}

public int update(User user) throws SQLException{

String sql = "update user set name=?, tele=?, birthday=? where id = "+user.getId();

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setString(2, user.getName());

pstmt.setString(3, user.getTele());

pstmt.setDate(4, user.getBirthday());

int n = pstmt.executeUpdate(sql);

pstmt.close();

return n;

}

public User getUser(Integer id) throws SQLException{

String sql = "select * from user where id = " + id;

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

User user = getUserFromResultSet(rs);

rs.close();

stmt.close();

return user;

}

static User getUserFromResultSet(ResultSet rs) throws SQLException{

Integer id = rs.getInt("id");

String name= rs.getString("name");

String tele= rs.getString("tele");

Date birthday = rs.getDate("birthday");

return new User(id, name, tele, birthday);

}

}

/**

* 构建数据库表的java类映射

*/

class User{

private Integer id;

private String name;

private String tele;

private Date birthday;

public User() {

}

public User(Integer id, String name, String tele, Date birthday) {

super();

this.id = id;

this.name = name;

this.tele = tele;

this.birthday = birthday;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTele() {

return tele;

}

public void setTele(String tele) {

this.tele = tele;

}

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值