未分类
2020-10-14 13:20:03
1822677238@qq.com
手机扫码查看
2020Javaweb教程之JDBC实现用户登录
import java.sql.*;
import java.util.Scanner;
public class JDBCforLogin {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名:");
String username=sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
login(username,password);
}
public static void login(String username,String password){
Connection connection=null;
PreparedStatement PreparedStatement=null;
ResultSet resultSet=null;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demos", "root", "root");
// ? 为占位符
String sql="select username,password from users where username=? and password=?";
// 预编译sql语句
PreparedStatement=connection.prepareStatement(sql);
//为每个占位符赋予一个值
PreparedStatement.setString(1,username);
PreparedStatement.setString(2,password);
resultSet = PreparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("登录成功");
}else System.out.println("登录失败");
}catch (Exception e){}finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (PreparedStatement != null) {
PreparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {}
}
}
}
- 本页地址 https://www.9713job.com/?p=2364
- 上一篇 <<2020Javaweb教程之JDBC
- 下一篇 >>2020Javaweb教程之JDBC总结



发表回复