4 回答
TA贡献13条经验 获得超4个赞
经过24小时的琢磨,终于弄懂了,我将我犯的错误放在这里,仅供大家参考,都是一些细节的错误,希望对大家有所帮助。
//“更新数据”方法
public void accountUpdate(Account a) throws Exception{
Connection conn=DBUtil.getConnection();
StringBuilder sb=new StringBuilder();
sb.append("update account_info set account=?,amount=? where id=?");
PreparedStatement ps=conn.prepareStatement(sb.toString());
ps.setString(1,a.getAccount());//与上面sql语句对应放在第一个传递
ps.setDouble(2, a.getAmount());//第二个传递
ps.setInt(3, a.getId());//第三个传递
ps.execute();
}
//获取带account、id、amount信息的Account对象
public Account get(Integer id) throws Exception{
Connection conn=DBUtil.getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select id,account,amount from account_info where id= ?");
PreparedStatement ps=conn.prepareStatement(sb.toString());
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
Account a=null;
while(rs.next()){
a=new Account();
a.setId(rs.getInt("id"));
a.setAccount(rs.getString("account"));
a.setAmount(rs.getDouble("amount"));
}
return a;
}
//调用方法
public class Test01 {
public static void main ( String[] args ) throws Exception {
Service service=new Service();
AccountAction a=new AccountAction();
Account from=null;
Account to=null;
from=a.get(1);
to=a.get(2);
service.trans(from, to, 20d);
System.out.println("账户Id: "+from.getId()+"账号:"+from.getAccount()+" 余额:"+from.getAmount());
}
}
//输出结果
账户Id: 1账号:a 余额:210.0
//同时数据库中的数据也同步更新了。
TA贡献13条经验 获得超4个赞
定义get()方法,获取from、to含有id,account、amount信息的对象
public Account get(Integer id) throws Exception{
Connection conn=DBUtil.getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select id,account,amount from account_info where id= ?");
PreparedStatement ps=conn.prepareStatement(sb.toString());
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
Account a=null;
while(rs.next()){
a=new Account();
a.setId(rs.getInt("id"));
a.setAccount(rs.getString("account"));
a.setAmount(rs.getDouble("amount"));
}
return a;
}
//调用trans(from,to,amount)方法
public class Test01 {
public static void main ( String[] args ) throws Exception {
Service service=new Service();
AccountAction a=new AccountAction();
Account from=null;
Account to=null;
from=a.get(1);
to=a.get(2);
service.trans(from, to, 20d);
}
}
运行的时候没有问题,大神们过来看看,怎么破啊,虽然是个小问题,可是不解决,就不能真正掌握jdbc呀,大家一起探讨吧。
添加回答
举报