1. 程式人生 > >JDBC增刪改查示例程式碼

JDBC增刪改查示例程式碼

  • 首先使用如下SQL語句生成一個users表
create table users(
	id int primary key auto_increment,
	name varchar(40),
	password varchar(40),
	email varchar(60),
	birthday date
)character set utf8 collate utf8_general_ci;

insert into users(name,password,email,birthday) values('zs','123456','[email protected]','1980-12-04'
); insert into users(name,password,email,birthday) values('lisi','123456','[email protected]','1981-12-04'); insert into users(name,password,email,birthday) values('wangwu','123456','[email protected]','1979-12-04');
  • 主函式
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.
sql.ResultSet; import java.util.ArrayList; import java.util.List; public class JDBC { public static void main(String[] args) { query(); insert(); update(); delete(); } public static void query() { Connection conn = null; PreparedStatement pstmt =
null; ResultSet rs = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement("select * from users"); rs = pstmt.executeQuery(); List<User> list = new ArrayList<>(); while (rs.next()) { User u = new User(); //ResultSet類中的一些方法,獲取各種型別的資料 u.setId(rs.getInt("id")); u.setName(rs.getString("name")); u.setPassword(rs.getString("password")); u.setBirthday(rs.getDate("birthday")); u.setEmail(rs.getString("email")); list.add(u); } for (User user : list) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeAll(rs, pstmt, conn); } } public static void update() { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement("update users set name = ?,password = ?,email = ? where id = ?"); //PreparedStatement類中的一些方法,設定SQL語句中問號位置的值 pstmt.setString(1, "jerry"); pstmt.setString(2, "123"); pstmt.setString(3, "[email protected]"); pstmt.setInt(4, 3); int i = pstmt.executeUpdate(); if (i > 0) { System.out.println("update success"); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeAll(null, pstmt, conn); } } public static void insert() { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement("insert into users values(?,?,?,?,?)"); //PreparedStatement類中的一些方法,設定SQL語句中問號位置的值 pstmt.setInt(1, 4); pstmt.setString(2, "tom"); pstmt.setString(3, "333"); pstmt.setString(4, "[email protected]"); pstmt.setString(5, "2018-10-10"); int i = pstmt.executeUpdate(); if (i > 0) { System.out.println("insert success"); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeAll(null, pstmt, conn); } } public static void delete() { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement("delete from users where id = ?"); pstmt.setInt(1,4);//刪除id為4的記錄 int id = pstmt.executeUpdate(); if (id>0){ System.out.println("delete success"); } } catch (Exception e) { e.printStackTrace(); }finally { DBUtils.closeAll(null,pstmt,conn); } } }
  • 輸出結果如下:
User{id=1, name='zs', password='123456', email='[email protected]', birthday=1980-12-04}
User{id=2, name='lisi', password='123456', email='[email protected]', birthday=1981-12-04}
User{id=3, name='wangwu', password='123456', email='[email protected]', birthday=1979-12-04}
insert success
update success
delete success
  • 其中用到的Users類
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(String email) {
        return this.email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
  • 其中用到的DBUtils類
import java.sql.*;
import java.util.ResourceBundle;

public class DBUtils {
    private static String url;
    private static String username;
    private static String password;

    static{
        //此物件是用於載入dbinfo.properties檔案中的資料
        ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
        url = rb.getString("url");//檔案中的資訊以字典的形式儲存
        username = rb.getString("username");
        password = rb.getString("password");

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //得到連線的方法
    public static Connection getConnection() throws Exception{
        return DriverManager.getConnection(url, username, password);
    }

    //關閉資源的方法
    public static void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn){
        //關閉資源
        if(rs!=null){
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            pstmt = null;
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}