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"