ja003

(一)从结果集获取数据的两种方法


			Statement stmt=con.createStatement();
			ResultSet rs=stmt.executeQuery("select * from product");
			
			while(rs.next()) {
				//从结果集获取数据的方法 (1)
				System.out.println(rs.getInt(1)+","+rs.getString(2)+"."+rs.getString(3));
				//方法(2)
				System.out.println(rs.getString("product_type"));
			}
			

(二)创建用户名和密码校验的查询方法

public class JDBCDemo01 {

	public static void main(String[] args) {
		//selectAll();
		System.out.println(selectByUsernamePassword("a", "g"));
	}
		
	
	public static boolean selectByUsernamePassword(String username,String password) {
		Connection con=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			//String url="jdbc:mysql://localhost:3306/web01";//有时候可能会乱码
			//解决乱码问题
			String url="jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC";
			
			 con=DriverManager.getConnection(url,"root","root");
			 stmt=con.createStatement();
			 String sql="select *from product where username= '"+username+"' and password= '"+password+"' ";
			rs=stmt.executeQuery(sql);
			if(rs.next()) {
				return true;
			}else {
				return false;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
			if(rs!=null)rs.close();
			if(stmt!=null)rs.close();
			if(con!=null)rs.close();
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
		return false;
	}
}

(三)sql注入攻击:

System.out.println(selectByUsernamePassword("a", "dg' or '1'='1 " ));//sql注入

解决方法:

con=DriverManager.getConnection(url,"root","root");
			 //查询sql语句的第二种方法
			 String sql="select * from product where username=? and password=? ";
			 
			 PreparedStatement pstmt=con.prepareStatement(sql);
			 pstmt.setString(1,username);
			 pstmt.setString(2,password);
			 
			rs= pstmt.executeQuery();
			 if(rs.next())return true;
			 else return false;

 

你可能感兴趣的:(java)