时间:2021-07-01 10:21:17 帮助过:27人阅读
1)封装数据库连接字符串 /** * JDBC配置信息 */ public class JdbcConfig { private String driverName; private String url; private String userName; private String password; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
public class DbUtil { /** * 取得Connection * @return */ public static Connection getConnection(){ Connection conn=null; try { //通过读取配置文件获取数据库连接字符串 JdbcConfig jdbcConfig=XmlConfigReader.getInstance().getJdbcConfig(); //加载驱动
Class.forName(jdbcConfig.getDriverName()); String url=jdbcConfig.getUrl(); String userName=jdbcConfig.getUserName(); String password=jdbcConfig.getPassword(); //建立连接 conn = (Connection) DriverManager.getConnection(url, userName, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } } 3)完成用户的添加操作 public class UserManager { /**
* 添加用户 */ public void addUser(User user){ //创建SQL语句 String sql="insert into t_user(user_id,user_name,password,contact_tel,email,create_date)"+ " values(?,?,?,?,?,?)"; Connection conn=null; PreparedStatement pstmt=null; try{ //获取Connection conn=DbUtil.getConnection(); pstmt=conn.prepareStatement(sql); //设置参数(这种方式可防止sql注入) pstmt.setString(1, user.getUserId()); pstmt.setString(2, user.getUserName()); pstmt.setString(3, user.getPassword()); pstmt.setString(4, user.getContactTel()); pstmt.setString(5, user.getEmail()); pstmt.setTimestamp(6, new Timestamp(System.currentTimeMillis())); //执行用户添加操作 pstmt.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); }finally{ DbUtil.close(pstmt); DbUtil.close(conn); } } }
JDBC 实战应用
标签:java j2ee