0
0

More than 1 year has passed since last update.

db insert

Last updated at Posted at 2023-02-07
public class Outer {
    public static void main(String[] args) {
        try {
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/data/Sample");
            try(con) {
                shokai(con);
                String sql = "insert into firsttable values (?, ?)";
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setInt(1,60);
                ps.setString(2,"sixty");
                int ret = ps.executeUpdate();
                System.out.println("insert count:" + ret);
                shokai(con);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
    static void shokai(Connection con) {
        try {
            String sql = "select * from firsttable";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println(id + ":" + name);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
}
10:TEN
20:TWENTY
30:THIRTY
40:xxx
50:fifty
insert count:1
10:TEN
20:TWENTY
30:THIRTY
40:xxx
50:fifty
60:sixty

executeQueryはexecute, getResultSet
exequteUpdateはexecute, getUpdateCount
に置き換えることができる
executeはResultSetをreturnしているかどうかをtrue/falseで返す

public class Outer {
    public static void main(String[] args) {
        try {
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/data/Sample");
            try(con) {
                shokai(con);
                String sql = "insert into firsttable values (?, ?)";
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setInt(1,50);
                ps.setString(2,"sixty");
                boolean bl = ps.execute();
                int cnt = ps.getUpdateCount();
                System.out.println("insert count:" + cnt);
                shokai(con);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
    static void shokai(Connection con) {
        try {
            String sql = "select * from firsttable";
            Statement st = con.createStatement();
            ResultSet rs = null;
            if(st.execute(sql))  rs = st.getResultSet();
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println(id + ":" + name);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0