jdbc连接数据库,使用通配符

来源:互联网 发布:htcg5软件 编辑:程序博客网 时间:2024/05/22 10:47

电脑的固态硬盘坏掉了,写的一年的java程序全都不见了,很多基础的知识都想不起来,忽然要用的时候又要重新去搜,搜到的还不知道能不能用,所以下定决心,学一个写一个!用博客记录下来!

废话不多说,直接上代码。首先自己写一个工具类;

包就一个:mysql 的驱动包

jdbc_Utils.class

package com.wzl.utils;import org.springframework.test.context.TestExecutionListeners;import java.sql.*;/** * Created by Administrator on 2017/3/19. */public class Jdbc_Utils {    private static String username="root";    private static String password="bobo";    private static Connection con;    private static ResultSet rest;    private static String driver="com.mysql.jdbc.Driver";    private static String url="jdbc:mysql://localhost:3306/springMvcMybatis?useUnicode=true&characterEncoding=utf8";    public static Connection getConnections() throws ClassNotFoundException, SQLException {        Class.forName(driver);        con= DriverManager.getConnection(url, username, password);        return con;    }    public static void closeAll(Connection con, ResultSet rest,PreparedStatement pst){        try {            if(con==null||con.isClosed()){                con.close();            }            if(rest==null||rest.equals("")){                rest.close();            }           /* if(st==null||st.equals("")){                st.close();            }*/            if(pst==null||pst.equals("")){                pst.close();            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

UserDaoImpl.class

package com.wzl.daoImpl;import com.wzl.dao.UserDao;import com.wzl.entity.User;import com.wzl.utils.Jdbc_Utils;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * Created by Administrator on 2017/3/19. */public class UserDaoImpl implements UserDao{        private Connection con;        private PreparedStatement prt;        private ResultSet rest;        private String sql="SELECT*FROM `user` WHERE username=? AND `password`=? ";        User user=new User();    public User login(String username, String password) throws SQLException, ClassNotFoundException {        con= Jdbc_Utils.getConnections();        prt=con.prepareStatement(sql);        prt.setString(1,username);        prt.setString(2,password);        rest=prt.executeQuery();        if(rest.next()){            int  id=rest.getInt(1);            String username1=rest.getString(2);            String password1=rest.getString(3);            String name=rest.getString(4);            String message=rest.getString(5);            user.setId(id);            user.setPassword(password1);            user.setUsername(username1);            user.setMessage(message);            user.setName(name);        }else{            user=null;        }        Jdbc_Utils.closeAll(con,rest,prt);        return user;    }}



0 0
原创粉丝点击