引入maven jdbc 依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency>
创建三个类:
Book为实体类,内容为属性和get(),set()方法
Function为方法类,内容为数据库连接,增删改查方法
Test是测试类
public class FunctionSet {
private static final String URL = "jdbc:mysql://localhost:xxxx/xxxx?useUnicode=true&characterEncoding=utf-8";
private static final String USER = "xxxx";
private static final String PASSWORD = "xxxx";
private static Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
public void getConn() throws SQLException {
try {
//1、加载驱动
Class.forName(driver);
//2、获得数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public List<Book> queryBookList() {
String sql = "select * from BOOK";
List<Book> list = new ArrayList<Book>();
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()){
String bookName = rs.getString("BookName");
Date rentTime = rs.getDate("RentTime");
String rentMan = rs.getString("RentMan");
System.out.println("书名:"+bookName+" 借阅时间:"+rentTime+" 借阅人:"+rentMan);
list.add(new Book(bookName,rentTime,rentMan));
}
rs.close();
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public void addBook(Book book) {
String addContext = "insert into BOOK(BookName,RentTime,RentMan) values (?,?,?)";
try {
PreparedStatement pst = conn.prepareStatement(addContext);
pst.setString(1,book.getBookName());
pst.setDate(2,book.getRentTime());
pst.setString(3,book.getRentMan());
pst.execute();
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteBook(String bookName) {
String sql = "delete from BOOK where BookName = ?";
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,bookName);
pst.execute();
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void modifyBook(Book book) {
int i = 0;
String sql = "update BOOK set RentTime = ?,RentMan = ? where BookName = ?";
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setDate(1,book.getRentTime());
pst.setString(2,book.getRentMan());
pst.setString(3,book.getBookName());
pst.execute();
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
FunctionSet functionSet = new FunctionSet();
try {
functionSet.getConn();
System.out.println("请输入要进行的操作");
Scanner scanner = new Scanner(System.in);
String s= scanner.next();
if (s.equals("增")){
functionSet.addBook(new Book("1", Date.valueOf("2009-12-11"),"3"));
}else if (s.equals("改")){
functionSet.modifyBook(new Book("1", Date.valueOf("2019-12-11"),"4"));
}else if (s.equals("删")){
functionSet.deleteBook("1");
}else if (s.equals("查")){
functionSet.queryBookList();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
程序执行起来
先增加两本书,再来查看
改书名为1的书
删除书名为1的书