JDBC登录验证数据库

jdbc连接数据库主要有以下几个步骤:

    1.导入mysql驱动包
    2. 注册驱动
    3. 获取数据库连接对象 Connection
    4. 定义sql
    5. 获取执行sql语句的对象 Statement
    6. 执行sql,接受返回结果
    7. 处理结果
    8. 释放资源


package www;

import java.sql.*;
import java.util.Scanner;

public class Login {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请依次输入账号,密码:");
String id = sc.next();
String pwd = sc.next();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try {
//1.注册加载(mysql5之后,注册加载可以不写)
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/s";
//2.获取连接
connection = DriverManager.getConnection(url,"root","root");
//3.执行sql
String sql = "select * from user where username=? and password=?";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1,id);
pstmt.setString(2,pwd);
//4.返回结果集
res = pstmt.executeQuery();
if (res.next()){
System.out.print(”登录成功!“)
}else {
System.out.println("登陆失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {

e.printStackTrace();
}

try {
//释放资源
res.close();
pstmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}

}
}


JDBC登录验证数据库

上一篇:pytest_addoption : 命令行参数


下一篇:Maven