底层jdbc查询操作

底层jdbc查询操作

@Test
    public void jdbcTest(){
    	Connection conn=null;
    	PreparedStatement ps=null;
    	ResultSet rs = null;
    	//加载驱动
    	try {
			Class.forName("com.mysql.jdbc.Driver");
			//创建连接
			conn=(Connection) DriverManager.getConnection("jdbc:mysql:///springday03","root","root");
			
	    	//编写sql语句
			String sql="select * from user where username=?";
			//预编译sql
			ps=(PreparedStatement) conn.prepareStatement(sql);
	    	//预编译设置
			ps.setString(1, "lucy");
			//执行sql
			rs=(ResultSet) ps.executeQuery();
			//遍历结果集
			while(rs.next()){
				String username=rs.getString("username");
				String password=rs.getString("password");
				
				//创建实体类对象,把参数存到实体类打印
				User user = new User();
				user.setUsername(username);
				user.setPassword(password);
				//重写toString方法输出user
				System.out.println(user);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭连接
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
    
    }


发布了126 篇原创文章 · 获赞 145 · 访问量 17万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章