| :
* To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javatpoint.rest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author User */ public class DbConnection { private static Connection con; private static Statement st; private static PreparedStatement pst; private static ResultSet rs; public static void main(String[] args) { List list = getStudents(); for (Student student : list) { System.out.println(student); } } public static List getStudents() { List list = new ArrayList<>(); try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restdb", "root", ""); st = con.createStatement(); rs = st.executeQuery("select * from student"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); Student student = new Student(id, name, age); list.add(student); } } catch (SQLException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); } return list; } public static void addStudent(Student student) { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restdb", "root", ""); pst = con.prepareStatement("insert into student (name, age) values (?,?)"); pst.setString(1, student.getName()); pst.setInt(2, student.getAge()); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); } } public static void updateStudent(Student student) { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restdb", "root", ""); pst = con.prepareStatement("update student set name = ?, age = ? where id = ?"); pst.setString(1, student.getName()); pst.setInt(2, student.getAge()); pst.setInt(3, student.getId()); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); } } public static void deleteStudent(int id) { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restdb", "root", ""); pst = con.prepareStatement("delete from student where id = ?"); pst.setInt(1, id); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); } } }
ǸҳܰȨ۳ʱ踶ѹ
˴
ɨ븶Ѽɸ
ѹ | | ʱʱ | | οʱ | ֤ | ر | û | Y.1731 | XnAP | X2AP | Web LMT |