您的位置:首页 > 其它

黑马day10 使用PrepareStatement增加&删除&更改

2015-06-29 21:41 281 查看
一个简单的小测试案例:

package cn.itheima.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import cn.itheima.utils.JDBCUtils;

public class JDBCDemo6 {
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;

	@Test
	public void update() {
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement("update user set name='程崇树' where name=?");
			ps.setString(1, "李卫康");
			ps.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			JDBCUtils.closeResource(rs, ps, con);
		}
	}

	@Test
	public void delete() {
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement("delete from user where name=?");
			ps.setString(1, "程崇树");
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			JDBCUtils.closeResource(rs, ps, con);
		}
	}

	@Test
	public void add() {
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement("insert into user values(2,?,?,?)");
			ps.setString(1, "李卫康");
			ps.setByte(2, (byte)1);
			ps.setDate(3, new Date(1992, 3, 4));
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			JDBCUtils.closeResource(rs, ps, con);
		}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: