jdbc mysql

Java代码 复制代码
  1. //最简单的JDBC MySQL   
  2. static void test() throws SQLException, ClassNotFoundException {   
  3.         //1.注册驱动   
  4.         //DriverManager.registerDriver(new com.mysql.jdbc.Driver());   
  5.         Class.forName("com.mysql.jdbc.Driver");   
  6.   
  7.         //2.建立连接   
  8.         //建立连接原则:晚建立,早释放   
  9.         Connection conn = DriverManager.getConnection(   
  10.                 "jdbc:mysql://localhost:3306/mydata""username""password");   
  11.            
  12.         //3创建语句   
  13.         Statement st = conn.createStatement();   
  14.            
  15.         //4.执行结果   
  16.         ResultSet rs = st.executeQuery("select * from customers");   
  17.            
  18.         //5.处理结果   
  19.         while (rs.next()) {   
  20.             System.out.println(rs.getObject(1) + "/t" + rs.getObject(2) + "/t" + rs.getObject(3));   
  21.         }   
  22.            
  23.         //6.释放资源   
  24.         rs.close(); st.close(); conn.close();   
  25.     }  
//最简单的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
把父类赋给子类是不可以的,所以要进行转型处理.

Java代码 复制代码
  1. static void create(int id, String name, Date bir, float money) throws Exception {   
  2.         Connection conn = null;   
  3.         PreparedStatement ps = null;   
  4.         ResultSet rs = null;   
  5.         try {   
  6.             conn = JdbcUtils.getConnection();   
  7.             // 3创建语句   
  8.             String sql = "insert into user values(?,?,?,?)";   
  9.             ps = conn.prepareStatement(sql);   
  10.             ps.setInt(1, id);   
  11.             ps.setString(2, name);   
  12.             //Date要进行转型处理   
  13.             ps.setDate(3new java.sql.Date(bir.getTime()));   
  14.             ps.setFloat(4, money);   
  15.   
  16.             // 4.执行结果   
  17.             int i = ps.executeUpdate();   
  18.             System.out.println("i=" + i);   
  19.         } finally {   
  20.             JdbcUtils.free(rs, ps, conn);   
  21.         }   
  22.     }  
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);
		}
	}



--------------------------------------------------
处理大文本

Java代码 复制代码
  1. //创建大文本   
  2.     static void create() throws Exception {   
  3.         Connection conn = null;   
  4.         PreparedStatement ps = null;   
  5.         ResultSet rs = null;   
  6.         try {   
  7.             conn = JdbcUtils.getConnection();   
  8.             // 3创建语句   
  9.             String sql = "insert into clob_txt(txt) values(?)";   
  10.             ps = conn.prepareStatement(sql);   
  11.             File file = new File("D:/Servlet Jsp/JDBC/src/Test.java");   
  12.             BufferedReader reader = new BufferedReader(new FileReader(file));   
  13.             ps.setCharacterStream(1, reader, (int)file.length());   
  14.   
  15.             // 4.执行结果   
  16.             int i = ps.executeUpdate();   
  17.             reader.close();   
  18.             System.out.println("i=" + i);   
  19.         } finally {   
  20.             JdbcUtils.free(rs, ps, conn);   
  21.         }   
  22.     }   
  23.        
  24.     //读取大文本   
  25.     static void read() throws Exception {   
  26.         Connection conn = null;   
  27.         Statement st = null;   
  28.         ResultSet rs = null;   
  29.         try {   
  30.             conn = JdbcUtils.getConnection();   
  31.             // 3创建语句   
  32.             String sql = "select txt from clob_txt";   
  33.             st = conn.createStatement();   
  34.             // 4.执行结果   
  35.             rs = st.executeQuery(sql);   
  36.   
  37.             // 5.处理结果   
  38.             while (rs.next()) {   
  39.                 Reader reader = rs.getCharacterStream(1);   
  40.                 File file = new File("D:/Servlet Jsp/JDBC/src/Test_bak.java");   
  41.                 Writer write = new BufferedWriter(new FileWriter(file));   
  42.                 char[] buf = new char[1024];   
  43.                 int len = reader.read(buf);   
  44.                 while (len != -1) {   
  45.                     write.write(buf);   
  46.                     len = reader.read(buf);   
  47.                 }   
  48.                 write.close();   
  49.                 reader.close();   
  50.             }   
  51.         } finally {   
  52.             JdbcUtils.free(rs, st, conn);   
  53.         }   
  54.     }  
//创建大文本
	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);
		}
	}



处理二进制数据

Java代码 复制代码
  1. static void create() throws Exception {   
  2.         Connection conn = null;   
  3.         PreparedStatement ps = null;   
  4.         ResultSet rs = null;   
  5.         try {   
  6.             conn = JdbcUtils.getConnection();   
  7.             // 3创建语句   
  8.             String sql = "insert into clob_bit(big_bit) values(?)";   
  9.             ps = conn.prepareStatement(sql);   
  10.             File file = new File("D:/Install/Temporary file/av-376345.jpg");   
  11.             InputStream in = new BufferedInputStream(new FileInputStream(file));   
  12.             ps.setBinaryStream(1, in, (int)file.length());   
  13.   
  14.             // 4.执行结果   
  15.             int i = ps.executeUpdate();   
  16.             in.close();   
  17.             System.out.println("i=" + i);   
  18.         } finally {   
  19.             JdbcUtils.free(rs, ps, conn);   
  20.         }   
  21.     }   
  22.        
  23.     static void read() throws Exception {   
  24.         Connection conn = null;   
  25.         Statement st = null;   
  26.         ResultSet rs = null;   
  27.         try {   
  28.             conn = JdbcUtils.getConnection();   
  29.             // 3创建语句   
  30.             String sql = "select big_bit from clob_bit";   
  31.             st = conn.createStatement();   
  32.             // 4.执行结果   
  33.             rs = st.executeQuery(sql);   
  34.   
  35.             // 5.处理结果   
  36.             while (rs.next()) {   
  37.                 InputStream in = rs.getBinaryStream(1);   
  38.                 File file = new File("D:/Install/av-376345_bak.jpg");   
  39.                 OutputStream out = new BufferedOutputStream(new FileOutputStream(file));   
  40.                 byte[] buf = new byte[1024];   
  41.                 int len = in.read(buf);   
  42.                 while (len != -1) {   
  43.                     out.write(buf);   
  44.                     len = in.read(buf);   
  45.                 }   
  46.                 out.close();   
  47.                 in.close();   
  48.             }   
  49.         } finally {   
  50.             JdbcUtils.free(rs, st, conn);   
  51.         }   
  52.     }  
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);
		}
	}


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

Sql代码 复制代码
  1. create table user  
  2. (   
  3. id int primary key auto_increment,   
  4. name varchar(30),   
  5. birthday date,   
  6. money float  
  7. );  
create table user
(
id int primary key auto_increment,
name varchar(30),
birthday date,
money float
);


Java代码 复制代码
  1. public class User {   
  2.     private int id;   
  3.     private String name;   
  4.     private Date birthday;   
  5.     private float money;   
  6.        
  7.     public int getId() {   
  8.         return id;   
  9.     }   
  10.        
  11.     public User setId(int id) {   
  12.         this.id = id;   
  13.            
  14.     }   
  15.        
  16.     public String getName() {   
  17.         return name;   
  18.     }   
  19.        
  20.     public User setName(String name) {   
  21.         this.name = name;   
  22.            
  23.     }   
  24.        
  25.     public Date getBirthday() {   
  26.         return birthday;   
  27.     }   
  28.        
  29.     public User setBirthday(Date birthday) {   
  30.         this.birthday = birthday;   
  31.            
  32.     }   
  33.        
  34.     public float getMoney() {   
  35.         return money;   
  36.     }   
  37.        
  38.     public User setMoney(float money) {   
  39.         this.money = money;   
  40.            
  41.     }   
  42. }  
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;
		
	}
}


Java代码 复制代码
  1. public interface UserDao {   
  2.     //添加用户   
  3.     public void addUser(User user);   
  4.        
  5.     //根据id查询用户   
  6.     public User getUser(int userId);   
  7.        
  8.     //根据用户名查询用户   
  9.     public User findUser(String loginName, String password);   
  10.        
  11.     //更新用户信息   
  12.     public void update(User user);   
  13.        
  14.     //删除用户   
  15.     public void delete(User user);   
  16. }  
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);
}


Java代码 复制代码
  1. public class UserDaoImpl implements UserDao {   
  2.   
  3.     public void addUser(User user) {   
  4.         Connection conn = null;   
  5.         PreparedStatement ps = null;   
  6.         ResultSet rs = null;   
  7.         try {   
  8.             conn = JdbcUtils.getConnection();   
  9.             String sql = "insert into user(name, birthday, money) values(?,?,?)";   
  10.             ps = conn.prepareStatement(sql);   
  11.             ps.setString(1, user.getName());   
  12.             ps.setDate(2new java.sql.Date(user.getBirthday().getTime()));   
  13.             ps.setFloat(3, user.getMoney());   
  14.             ps.executeUpdate();   
  15.         }catch(SQLException e){   
  16.             throw new DaoException(e.getMessage(), e);   
  17.         } finally {   
  18.             JdbcUtils.free(rs, ps, conn);   
  19.         }   
  20.            
  21.     }   
  22.   
  23.     public void delete(User user) {   
  24.         Connection conn = null;   
  25.         Statement st = null;   
  26.         ResultSet rs = null;   
  27.         try {   
  28.             conn = JdbcUtils.getConnection();   
  29.             st = conn.createStatement();   
  30.             String sql = "delete from user where id =" + user.getId();   
  31.             st.executeUpdate(sql);   
  32.         } catch(SQLException e){   
  33.             throw new DaoException(e.getMessage(), e);   
  34.         } finally {   
  35.             JdbcUtils.free(rs, st, conn);   
  36.         }   
  37.     }   
  38.   
  39.     public User findUser(String loginName, String password) {   
  40.         Connection conn = null;   
  41.         PreparedStatement ps = null;   
  42.         ResultSet rs = null;   
  43.         User user = null;   
  44.         try {   
  45.             conn = JdbcUtils.getConnection();   
  46.             // 3创建语句   
  47.             String sql = "select id, name, birthday, money from user where name =?";   
  48.             ps = conn.prepareStatement(sql);   
  49.             ps.setString(1, loginName);   
  50.             // 4.执行结果   
  51.             rs = ps.executeQuery();   
  52.   
  53.             // 5.处理结果   
  54.             while (rs.next()) {   
  55.                 user = mappingUser(rs);   
  56.             }   
  57.         } catch(SQLException e){   
  58.             throw new DaoException(e.getMessage(), e);   
  59.         } finally {   
  60.             JdbcUtils.free(rs, ps, conn);   
  61.         }   
  62.         return user;   
  63.     }   
  64.   
  65.     public User getUser(int userId) {   
  66.         Connection conn = null;   
  67.         PreparedStatement ps = null;   
  68.         ResultSet rs = null;   
  69.         User user = null;   
  70.         try {   
  71.             conn = JdbcUtils.getConnection();   
  72.             // 3创建语句   
  73.             String sql = "select id, name, birthday, money from user where id =?";   
  74.             ps = conn.prepareStatement(sql);   
  75.             ps.setInt(1, userId);   
  76.             // 4.执行结果   
  77.             rs = ps.executeQuery();   
  78.   
  79.             // 5.处理结果   
  80.             while(rs.next()) {   
  81.                 user = mappingUser(rs);   
  82.             }   
  83.         } catch(SQLException e){   
  84.             throw new DaoException(e.getMessage(), e);   
  85.         } finally {   
  86.             JdbcUtils.free(rs, ps, conn);   
  87.         }   
  88.         return user;   
  89.     }   
  90.   
  91.     private User mappingUser(ResultSet rs) throws SQLException {   
  92.         User user = new User();   
  93.         user.setId(rs.getInt("id"));   
  94.         user.setName(rs.getString("name"));   
  95.         user.setBirthday(rs.getDate("birthday"));   
  96.         user.setMoney(rs.getFloat("money"));   
  97.         return user;   
  98.     }   
  99.   
  100.     public void update(User user) {   
  101.         Connection conn = null;   
  102.         PreparedStatement ps = null;   
  103.         ResultSet rs = null;   
  104.         try {   
  105.             conn = JdbcUtils.getConnection();   
  106.             String sql = "update user set name=?,birthday=?,money=? where id = ?";   
  107.             ps = conn.prepareStatement(sql);   
  108.             ps.setString(1, user.getName());   
  109.             ps.setDate(2new java.sql.Date(user.getBirthday().getTime()));   
  110.             ps.setFloat(3, user.getMoney());   
  111.             ps.setInt(4, user.getId());   
  112.                
  113.             ps.executeUpdate();   
  114.         } catch(SQLException e){   
  115.             throw new DaoException(e.getMessage(), e);   
  116.         } finally {   
  117.             JdbcUtils.free(rs, ps, conn);   
  118.         }   
  119.     }   
  120.   
  121. }  
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);
		}
	}

}


Java代码 复制代码
  1. public class DaoException extends RuntimeException {   
  2.   
  3.     public DaoException() {   
  4.         super();   
  5.     }   
  6.   
  7.     public DaoException(String message, Throwable cause) {   
  8.         super(message, cause);   
  9.     }   
  10.   
  11.     public DaoException(String message) {   
  12.         super(message);   
  13.     }   
  14.   
  15.     public DaoException(Throwable cause) {   
  16.         super(cause);   
  17.     }   
  18.   
  19. }  
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);
	}

}



测试类

Java代码 复制代码
  1. public class TestUserDao {   
  2.   
  3.     public static void main(String[] args) {   
  4.         //UserDao ud = DaoFactory.getInstance().getUserDao();   
  5.         UserDao ud = new UserDaoImpl();   
  6.            
  7.         //创建一个user   
  8.         User user3 = new User();   
  9.         user3.setName("bob7");   
  10. user3 .setBirthday(new Date());   
  11. user3.setMoney(1000.0f);   
  12.            
  13.         //添加用户   
  14.         ud.addUser(user3);   
  15.            
  16.         //更新用户   
  17.         User u = ud.getUser(11);   
  18.         u.setMoney(999.0f);   
  19.         ud.update(u);   
  20.            
  21.         //通过 id删除用户   
  22.         ud.delete(ud.getUser(9));   
  23.     }   
  24.   
  25. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值