实验内容:利用Statement演示SQL
实验要求:
1. =演示用户登录功能;
2. 用户输入用户名,如tom;用户输入密码,如123,成功登录,显示success!;否则登录不成功,显示error!
3. 演示SQL,用户名输入:jack ‘ or 1=1 -- ,密码输入:345,成功登录,显示success!
【贴代码】
package com;
import java.sql.*;
import java.util.Scanner;
public class Jdbc {
private final String URL="jdbc:mysql://localhost:3306/mon";
private final String USER="root";
private final String PWD="1234";
public void login() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL,USER,PWD);
stmt=con.createStatement();
Scanner input = new Scanner(System.in);
System.out.println("input user:");
String u=input.nextLine();
System.out.println("input pwd:");
String p=input.nextLine();
String sql="select count(*) from login where user='"+u+"' and pwd='"+p+"'";
rs=stmt.executeQuery(sql);
int c=-1;
if(rs.next()) {
c=rs.getInt(1);
}
if(c>0) {
System.out.println("success!");
} else {
System.out.println("error!");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
if(stmt!=null) rs.close();
if(con!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Jdbc b= new Jdbc();
b.login();
}
}
|