jdbc for mysql

  注册驱动(只做一次)
  建立连接(Connection)
  创建执行 SQL的语句(Statement)
  执行查询(executeQuery)
  处理执行结果(ResultSet)
  释放资源


//最简单的JDBC MySQL
static void test() throws SQLException, ClassNotFoundException {
		//1.注册驱动
		//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		Class.forName("com.mysql.jdbc.Driver");

		//2.建立连接
        //建立连接原则:晚建立,早释放
		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/mydata", "username", "password");
		
		//3创建语句
		Statement st = conn.createStatement();
		
		//4.执行结果
		ResultSet rs = st.executeQuery("select * from customers");
		
		//5.处理结果
		while (rs.next()) {
			System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" + rs.getObject(3));
		}
		
		//6.释放资源
		rs.close(); st.close(); conn.close();
	}


--------------------------------------------------

日期处理
"ps.setDate"要求传入的是 java.sql 里面的Date, 而“Date bir”是util里面的Date
把父类赋给子类是不可以的,所以要进行转型处理.

static void create(int id, String name, Date bir, float money) throws Exception {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "insert into user values(?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.setString(2, name);
			//Date要进行转型处理
			ps.setDate(3, new java.sql.Date(bir.getTime()));
			ps.setFloat(4, money);

			// 4.执行结果
			int i = ps.executeUpdate();
			System.out.println("i=" + i);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}


--------------------------------------------------
处理大文本
//创建大文本
	static void create() throws Exception {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "insert into clob_txt(txt) values(?)";
			ps = conn.prepareStatement(sql);
			File file = new File("D:/Servlet Jsp/JDBC/src/Test.java");
			BufferedReader reader = new BufferedReader(new FileReader(file));
			ps.setCharacterStream(1, reader, (int)file.length());

			// 4.执行结果
			int i = ps.executeUpdate();
			reader.close();
			System.out.println("i=" + i);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
	
	//读取大文本
	static void read() throws Exception {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "select txt from clob_txt";
			st = conn.createStatement();
			// 4.执行结果
			rs = st.executeQuery(sql);

			// 5.处理结果
			while (rs.next()) {
				Reader reader = rs.getCharacterStream(1);
				File file = new File("D:/Servlet Jsp/JDBC/src/Test_bak.java");
				Writer write = new BufferedWriter(new FileWriter(file));
				char[] buf = new char[1024];
				int len = reader.read(buf);
				while (len != -1) {
					write.write(buf);
					len = reader.read(buf);
				}
				write.close();
				reader.close();
			}
		} finally {
			JdbcUtils.free(rs, st, conn);
		}
	}



-----------------------------------------------------

处理二进制数据

static void create() throws Exception {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "insert into clob_bit(big_bit) values(?)";
			ps = conn.prepareStatement(sql);
			File file = new File("D:/Install/Temporary file/av-376345.jpg");
			InputStream in = new BufferedInputStream(new FileInputStream(file));
			ps.setBinaryStream(1, in, (int)file.length());

			// 4.执行结果
			int i = ps.executeUpdate();
			in.close();
			System.out.println("i=" + i);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
	
	static void read() throws Exception {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "select big_bit from clob_bit";
			st = conn.createStatement();
			// 4.执行结果
			rs = st.executeQuery(sql);

			// 5.处理结果
			while (rs.next()) {
				InputStream in = rs.getBinaryStream(1);
				File file = new File("D:/Install/av-376345_bak.jpg");
				OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
				byte[] buf = new byte[1024];
				int len = in.read(buf);
				while (len != -1) {
					out.write(buf);
					len = in.read(buf);
				}
				out.close();
				in.close();
			}
		} finally {
			JdbcUtils.free(rs, st, conn);
		}
	}


--------------------------------------------------


create table user
(
id int primary key auto_increment,
name varchar(30),
birthday date,
money float
);


public class User {
	private int id;
	private String name;
	private Date birthday;
	private float money;
	
	public int getId() {
		return id;
	}
	
	public User setId(int id) {
		this.id = id;
		
	}
	
	public String getName() {
		return name;
	}
	
	public User setName(String name) {
		this.name = name;
		
	}
	
	public Date getBirthday() {
		return birthday;
	}
	
	public User setBirthday(Date birthday) {
		this.birthday = birthday;
		
	}
	
	public float getMoney() {
		return money;
	}
	
	public User setMoney(float money) {
		this.money = money;
		
	}
}


public interface UserDao {
	//添加用户
	public void addUser(User user);
	
	//根据id查询用户
	public User getUser(int userId);
	
	//根据用户名查询用户
	public User findUser(String loginName, String password);
	
	//更新用户信息
	public void update(User user);
	
	//删除用户
	public void delete(User user);
}


public class UserDaoImpl implements UserDao {

	public void addUser(User user) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "insert into user(name, birthday, money) values(?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
			ps.setFloat(3, user.getMoney());
			ps.executeUpdate();
		}catch(SQLException e){
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
		
	}

	public void delete(User user) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			st = conn.createStatement();
			String sql = "delete from user where id =" + user.getId();
			st.executeUpdate(sql);
		} catch(SQLException e){
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, st, conn);
		}
	}

	public User findUser(String loginName, String password) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User user = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "select id, name, birthday, money from user where name =?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, loginName);
			// 4.执行结果
			rs = ps.executeQuery();

			// 5.处理结果
			while (rs.next()) {
				user = mappingUser(rs);
			}
		} catch(SQLException e){
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
		return user;
	}

	public User getUser(int userId) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User user = null;
		try {
			conn = JdbcUtils.getConnection();
			// 3创建语句
			String sql = "select id, name, birthday, money from user where id =?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, userId);
			// 4.执行结果
			rs = ps.executeQuery();

			// 5.处理结果
			while(rs.next()) {
				user = mappingUser(rs);
			}
		} catch(SQLException e){
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
		return user;
	}

	private User mappingUser(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("id"));
		user.setName(rs.getString("name"));
		user.setBirthday(rs.getDate("birthday"));
		user.setMoney(rs.getFloat("money"));
		return user;
	}

	public void update(User user) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "update user set name=?,birthday=?,money=? where id = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
			ps.setFloat(3, user.getMoney());
			ps.setInt(4, user.getId());
			
			ps.executeUpdate();
		} catch(SQLException e){
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}

}


public class DaoException extends RuntimeException {

	public DaoException() {
		super();
	}

	public DaoException(String message, Throwable cause) {
		super(message, cause);
	}

	public DaoException(String message) {
		super(message);
	}

	public DaoException(Throwable cause) {
		super(cause);
	}

}


public class TestUserDao {

	public static void main(String[] args) {
		//UserDao ud = DaoFactory.getInstance().getUserDao();
		UserDao ud = new UserDaoImpl();
		
		//创建一个user
		User user3 = new User();
		user3.setName("bob7");
user3 .setBirthday(new Date());
user3.setMoney(1000.0f);
		
		//添加用户
		ud.addUser(user3);
		
		//更新用户
		User u = ud.getUser(11);
		u.setMoney(999.0f);
		ud.update(u);
		
		//通过 id删除用户
		ud.delete(ud.getUser(9));
	}

}

你可能感兴趣的:(sql,mysql,jsp,jdbc,idea)