创建user表
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32));
properties文件配置数据库信息
url=jdbc:mysql://localhost:3306/db4
user=root
password=root
driver=com.mysql.jdbc.Driver //可有可无
JDBC工具类
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
//静态代码块
static {
Properties pro = new Properties();
//用类加载器中的方法找到jdbc.properties的路径,再用URL中的方法获取绝对路径
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resource = classLoader.getResource("jdbc.properties");
String path = resource.getPath();
try {
pro.load(new FileReader(path));
} catch (IOException e) {
e.printStackTrace();
}
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
try {
Class.forName(driver); //注册驱动,可不写
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void close(Statement stmt, Connection coon) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (coon != null) {
try {
coon.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection coon, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (coon != null) {
try {
coon.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
LoginDemo
import cn.itcast.util.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class LoginDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String name = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
login(name,password);
}
public static void login(String name, String password) {
Connection coon = null;
Statement stmt = null;
ResultSet rs = null;
try {
coon = JDBCUtils.getConnection();
stmt = coon.createStatement();
String sql = "select * from user where username = '" + name + "' and password = '" + password + "'";
rs = stmt.executeQuery(sql);
if(rs.next()){
System.out.println("登录成功");
}else{
System.out.println("用户名或密码错误");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(stmt,coon,rs);
}
}
}