package com.ljb.dao;
import com.ljb.model.User;;import java.sql.*;
public class UserSelectdao {
public User selectUserByName(String username){
User user=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;//结果集合对象,用于封装数据库查询结果
String sql="";
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","password");
sql="select * from user where username=?";
ps=conn.prepareStatement(sql);
ps.setString(1,username);
rs=ps.executeQuery();//执行数据库的查询语句并返回查询结果
while(rs.next()) {//让光标向下移动一次并判断下一个元素是否有值,有值则返回真
user =new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try{
ps.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
return user;
}
}