用eclipse和sqlserver实现图书管理系统的代码
时间: 2023-12-07 12:04:04 浏览: 187
由于图书管理系统的代码涉及到很多细节和具体实现,我无法在这里一一列出。但是,我可以提供一些参考代码,帮助你入门。
1. 连接到SQL Server数据库
```
import java.sql.*;
public class DBConnection {
private Connection conn = null;
private String url = "jdbc:sqlserver://localhost:1433;databaseName=bookdb";
private String user = "sa";
private String password = "123456";
public Connection getConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
```
2. 向数据库中添加图书记录
```
import java.sql.*;
public class BookDAO {
private Connection conn = null;
public BookDAO() {
DBConnection db = new DBConnection();
conn = db.getConnection();
}
public void addBook(Book book) {
try {
String sql = "INSERT INTO book (title, author, price) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, book.getTitle());
stmt.setString(2, book.getAuthor());
stmt.setDouble(3, book.getPrice());
stmt.executeUpdate();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. 获取数据库中所有图书记录
```
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BookDAO {
private Connection conn = null;
public BookDAO() {
DBConnection db = new DBConnection();
conn = db.getConnection();
}
public List<Book> getAllBooks() {
List<Book> list = new ArrayList<Book>();
try {
String sql = "SELECT * FROM book";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt("id"));
book.setTitle(rs.getString("title"));
book.setAuthor(rs.getString("author"));
book.setPrice(rs.getDouble("price"));
list.add(book);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
```
这些代码只是一个简单的参考,具体实现还需要根据你的需求来修改和完善。希望对你有所帮助!
阅读全文