07.26 用户登录 java mysql
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Login {
public static void main(String[] args) throws SQLException {
Scanner scanner = new Scanner(System.in);
System.out.println("--------------------用户登录-----------------");
System.out.println("请输入用户名:");
String username = scanner.next();
System.out.println("请输入密码:");
String psw = scanner.next();
Connection conn= null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "199702110";
PreparedStatement pstmt = null;
String sql = "select * from user where username = ? and password = ? ";
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, psw);
rs = pstmt.executeQuery();
if(rs.next()) {
System.out.println(username +"登录成功!");
}else {
System.out.println("用户名或密码错误!");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
pstmt.close();
conn.close();
}
}
}