原理
- 将建立连接和关闭连接的过程封装在DBUtils工具类里
- 常规statement无法进行人机交互 无法键盘交互 引入preparestatement
代码
DBUtils类
package com.tyut.common;
import java.sql.*;
public class DBUtils {
public static Connection getConnection() throws SQLException { //注意static 否则不能用类名调用
String url="jdbc:mysql://localhost:3306/test01";
String username="root";
String userpwd="123456";
try{
Connection conn = DriverManager.getConnection(url,username,userpwd);
return conn;
}catch(SQLException e){
e.printStackTrace();
}
return null;
}
/**
* @author xxx
* @version 1.0
* @date 2021.9.30
* @param rs
* @param st
* @param conn
*/
public static void close(ResultSet rs, Statement st, Connection conn){
try{
if(rs!=null)
rs.close();
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
JDBCDemo_Login_PrepareStatement类
package com.tyut.demo_jdbc;
import com.tyut.common.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCDemo_Login_PrepareStatement {
public static void main(String[] args) throws Exception {
//常规statement无法进行人机交互 无法键盘交互 引入preparestatement
/**
* 创建键盘输入
*/
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名:");
String username=sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
/**
* 使用工具类JDBCUtils中的方法getConnection获取数据库连接 直接用类名调用
*/
Connection conn= DBUtils.getConnection();
String sql="select * from user where username=? and password=?";//注意 是? 底下通过函数setObject()给?传参数
PreparedStatement pst=null; //创建preparedstatement对象 通过preparedstatement对象执行语句
ResultSet rs=null; //结果集
try{
pst=conn.prepareStatement(sql);
pst.setObject(1,username);//第一个参数传username
pst.setObject(2,password);//第二个参数传password
rs = pst.executeQuery();
/**
* 处理查询结果
*/
if(rs.next()){
System.out.println("登陆成功");
System.out.println("用户名:"+rs.getString("username"));
System.out.println("密码:"+rs.getString("password"));
}
}catch (SQLException e){
e.printStackTrace();
}finally {
//关闭结果集ResultSet,Preparedment,Connection
DBUtils.close(rs,pst,conn);
//关闭Scanner
sc.close();
}
}
}