代码:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; /* * 使用prepareStatement * */ public class Demo2Test { public static void main(String[] args) throws SQLException { //从控制台输入用户名和密码 Scanner sc=new Scanner(System.in); System.out.println("请输入用户名"); String name= sc.nextLine(); System.out.println("请输入密码"); String password=sc.nextLine(); //登陆的方法 login(name ,password); } private static void login(String name,String password) throws SQLException { Connection conn = JdbcUtils.getConnection(); //编写sql语句,未知内容使用?占位符; 用户名 密码 String s = "select * from user3 where sname=? and sid=?"; //获得PreparedStatement对象 PreparedStatement ps = conn.prepareStatement(s); //设置实际的参数,setxxx(占位符的位置,真实的值) ps.setString(1,name); ps.setString(2,password); //执行sql语句 ResultSet re =ps.executeQuery(); if (re.next()){ System.out.println("登陆成功"); }else { System.out.println("登录失败"); } //关闭资源 JdbcUtils.close(re,ps,conn); } }
工具类:
import java.sql.*; /* * 访问数据库工具类 * */ public class JdbcUtils { //把几个字符串定义成常量 private static final String USER="root"; private static final String PWD="root"; private static final String URl="jdbc:mysql://localhost:3306/day97"; private static final String DRIVER="com.mysql.jdbc.Driver"; static { try { //注册驱动 Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //得到数据库连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URl,USER,PWD); } //关闭连接、执行的打开资源 public static void close(Connection connection, Statement statement){ if (statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭所有打开资源 public static void close(ResultSet resultSet, Statement statement, Connection connection){ if (resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭资源 public static void close(PreparedStatement preparedStatement, Connection connection) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }