1.一个控制台的登陆案例:
public class LoginDBC {public static void main(String[] args) throws ClassNotFoundException, SQLException {Scanner scanner=new Scanner(System.in);System.out.println("请输入用户名");String username=scanner.next();System.out.println("请输入密码");String password=scanner.next();Class.forName("com.mysql.jdbc.Driver");Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb","root", "123");Statement statement=connection.createStatement();ResultSet resultSet = statement.executeQuery("select * from users where username='" + username + "'" + "and password='" + password + "'");if(resultSet.next())//证明查询到了数据.{System.out.println("登陆成功");}else{System.out.println("失败");}resultSet.close();statement.close();connection.close();}
但是有个sql注入问题,在输入用户名的时候如果输入
abc' or 1=1; #
代入回去 sql语句变成了
select * from users where username='abc' or 1=1 # ' and password=' password'
发生了sql注入问题,后面的密码判定被注释了,总是为true的登陆成功。
我们要使sql语句在用户输入数据前就编译成完整的sql语句 在进行填充数据。
二:preparestatement
解决了sql注入问题,更加高效,更加安全。用?占位符来动态绑定数据。
String sql="select * from user where username=?";
preparestatement pst=connection.preparestatment(sql);
pst.setString(1,"xiao"); #setXXX方法将第二个参数代替对应序号的?
解析完了之后可以重复使用
三:封装工具
在src目录下新建db.properties
文件内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/companydb?useUnicode=true& characterEncoding=utf8
username=root
password=123
public class DBUtils{
private static final Properties PROPERTIES=new Properties();
static{
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);
Class.forName("com.mysql.jdbc.Driver");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
String url=PROPERTIES.getProperty("url");
String username=PROPERTIES.getProperty("username");
String password=PROPERTIES.getProperty("password");
Connection connection= null;
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet)
{
if(resultSet!=null)
{
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null)
{
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null)
{
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}