代码目录结构:
domain javabean;
util 工具类 jdbcUtil是连接数据mysql数据库的工具类
dbcfg.properties是数据库的参数信息
dbcfg.properties
最重要的jdbutil
- package com.itheima.util;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.Properties;
- public class JdbcUtil {
- private static String driverClassName;
- private static String url;
- private static String username;
- private static String password;
- static{
- //为以上参数赋值
- try {
- InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbcfg.properties");
- Properties props = new Properties();
- props.load(in);
- driverClassName = props.getProperty("driverClassName");
- url = props.getProperty("url");
- username = props.getProperty("username");
- password = props.getProperty("password");
- Class.forName(driverClassName);//注册驱动
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- public static Connection getConnection() throws Exception{
- return DriverManager.getConnection(url, username, password);//连接
- }
- //释放资源
- public static void release(ResultSet rs,Statement stmt,Connection conn){
- if(rs!=null){
- try{
- rs.close();
- }catch(Exception e){
- }
- rs=null;
- }
- if(stmt!=null){
- try{
- stmt.close();
- }catch(Exception e){
- }
- stmt=null;
- }
- if(conn!=null){
- try{
- conn.close();
- }catch(Exception e){
- }
- conn=null;
- }
- }
- }
User实例
- package com.itheima.domain;
- import java.util.Date;
- public class User {
- private int id;
- private String name;
- private String password;
- private String email;
- private Date birthday;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- }
数据库操作CURD
- package com.itheima;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import org.junit.Test;
- import com.itheima.util.JdbcUtil;
- //对USers表进行CRUD操作
- public class Demo4 {
- @Test
- public void testAdd(){
- Connection conn = null;
- Statement stmt = null;