首先,创建数据库db_diary
第一步:写个工具类DbUtil,用于连接数据库
package com.java1234.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
public Connection getCon() throws Exception{
Class.forName(PropertiesUtil.getValue("jdbcName"));
Connection con=DriverManager.getConnection(PropertiesUtil.getValue("dbUrl"), PropertiesUtil.getValue("dbUserName"), PropertiesUtil.getValue("dbPassword"));
return con;
}
public void closeCon(Connection con)throws Exception{
if(con!=null){
con.close();
}
}
public static void main(String[] args) {
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("数据库连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
}
这里面用到了配置文件diary.properties
dbUrl=jdbc:mysql://localhost:3306/db_diary
dbUserName=root
dbPassword=root
jdbcName=com.mysql.jdbc.Driver
pageSize=4
imageFile=userImages/
imagePath=D:\Diary\WebContent\userImages\
第二步:写dao层UserDao,操作数据库
package com.java1234.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.java1234.model.User;
import com.java1234.util.PropertiesUtil;
public class UserDao {
public User login(Connection con,User user)throws Exception{
User resultUser=null;
String sql="select * from t_user where userName=? and password=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
resultUser=new User();
resultUser.setUserId(rs.getInt("userId"));
resultUser.setUserName(rs.getString("userName"));
resultUser.setPassword(rs.getString("password"));
resultUser.setNickName(rs.getString("nickName"));
resultUser.setImageName(PropertiesUtil.getValue("imageFile")+rs.getString("imageName"));
resultUser.setMood(rs.getString("mood"));
}
return resultUser;
}