首页 > 代码库 > JDBC基础二

JDBC基础二

1.配置文件:dbinfo.properties

driverClass=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/testusername=rootpassword=root

2.DBUtils.java

package com.mf.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ResourceBundle;public class DBUtils {	private static String driverClass;	private static String url;	private static String username;	private static String password;	static{		//此对象是用于加载properties文件数据的		ResourceBundle rb = ResourceBundle.getBundle("dbinfo");		driverClass = rb.getString("driverClass");		url = rb.getString("url");		username = rb.getString("username");		password = rb.getString("password");		try {			Class.forName(driverClass);		} catch (ClassNotFoundException e) {			e.printStackTrace();		}	}		//得到连接的方法	public static Connection getConnection() throws Exception{		return DriverManager.getConnection(url, username, password);	}	//关闭资源的方法	public static void closeAll(ResultSet rs,Statement stmt,Connection conn){		//关闭资源		if(rs!=null){			try {				rs.close();			} catch (Exception e) {				e.printStackTrace();			}			rs = null;		}		if(stmt!=null){			try {				stmt.close();			} catch (Exception e) {				e.printStackTrace();			}			stmt = null;		}		if(conn!=null){			try {				conn.close();			} catch (Exception e) {				e.printStackTrace();			}			conn = null;		}	}}

3.解决sql注入问题

public class DoLogin {		/**	 * 根据用户名和密码查询用户对象信息	 * @param name	 * @param pwd	 * @return u	 */	public User findUser(String name,String pwd){		Connection conn = null;		PreparedStatement stmt = null;		ResultSet rs = null;		User u = null;		try {			conn = DBUtils.getConnection();//得到连接对象Connection			String sql ="SELECT * FROM users WHERE NAME=? AND PASSWORD=?";			stmt = conn.prepareStatement(sql);//得到执行sql语句的对象Statement			//给?赋值			stmt.setString(1, name);						rs = stmt.executeQuery();//执行sql语句			if(rs.next()){				u = new User();				u.setId(rs.getInt(1));				u.setName(rs.getString(2));				u.setPassword(rs.getString(3));				u.setEmail(rs.getString(4));				u.setBirthday(rs.getDate(5));			}		} catch (SQLException e) {			e.printStackTrace();		}finally{			DBUtils.closeAll(rs, stmt, conn);		}		return u;	}

  

 

JDBC基础二