使用PreparedStatement 防止SQL攻击 实现预编译功能提高性能

public boolean login(String username,String password) throws Exception
{
    String driverClassName="com.mysql.jdbc.Driver";

    String url="jdbc:mysql://localhost:3306/mydb3";

    String u="root";

    String p="123";

    Class.forName(driverClassName);

    Connection connection=DriverManager.getConnection(url, u, p);

    String sql="SELECT * FROM user where username=? AND password=?";

    PreparedStatement preparedStatement=connection.prepareStatement(sql);

    preparedStatement.setString(1,username);
    preparedStatement.setString(2,password);

    ResultSet resultSet=preparedStatement.executeQuery();

    return resultSet.next();
}

@Test
public void fun() throws Exception
{
    String username="zhangSan";
    String password="1234789";
    System.out.println(login(username, password));
}
}

tips 1:有返回值的函数不能写注解@Test,否则会报函数参数必须为空的异常
2:传统的Statement在每次执行executeQuery(sql)都需要进行重新效验语法并编译成相应函数代码,降低了效率。
3:若使用PreparedStatement ,可以实现一次编译函数代码,而后的过程仅仅是给出函数参数,大大提高了效率。
4:第3点效率的提高是基于MySql数据库开启预编译功能。

如何开启数据库预编译功能呢?

使用以下url即可

String url="jdbc:mysql://localhost:3306/mydb3?useServerPrepStmts=true&cachePrepStmts=true"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章