Java实现对mysql中的数值进行读取、插入、更新、删除
public static void readdata(Connection con)//读取数据 { try { Statement statement = con.createStatement(); String sql = "select * from b_sim"; ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------"); System.out.println("序号" + "\t" + "名称" + "\t" + "楼层" + "\t" + "位置"); System.out.println("-----------------"); int number = 0; String name = null; String floor = null; String position = null; while(rs.next()){ number = rs.getInt("number"); name = rs.getString("name"); floor = rs.getString("floor"); position = rs.getString("position"); System.out.println(number + "\t" + name + "\t" + floor + "\t" + position); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void insertdata(Connection con)//插入数据 { try { PreparedStatement psql = con.prepareStatement("insert into b_sim (number,name,floor,position)" + "values(?,?,?,?)"); psql.setInt(1, 102); psql.setString(2, "Tony"); psql.setString(3, "1"); psql.setString(4, "大厅"); psql.executeUpdate(); psql.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void updatedata(Connection con)//更新数据 { try { PreparedStatement psql = con.prepareStatement("update b_sim set name = ? where number = ?"); psql.setString(1, "Tony"); psql.setInt(2, 102); psql.executeUpdate(); psql.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void deletedata(Connection con)//删除数据 { try { PreparedStatement psql = con.prepareStatement("delete from b_sim where number = ?"); psql.setInt(1, 102); psql.executeUpdate(); psql.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { Connection con; String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC"; //MySQL用户名 String user = "root"; //MySQL的密码 String password = "zsy0702"; try { Class.forName(driver); con = DriverManager.getConnection(url, user, password); //读取数据 readdata(con); //插入数据 insertdata(con); //更新数据 updatedata(con); //删除数据 deletedata(con); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
上面就是java中对MySQL中的数据进行读取、插入、更新、删除的操作,以上仅供参考,具体以自己实际操作进行修改。