java与mysql数据库增加图书功能怎么写
时间: 2023-12-31 12:03:46 浏览: 19
首先,您需要在Java中连接MySQL数据库。您可以使用JDBC API来实现这一点。以下是一个简单的连接示例:
```java
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "password");
System.out.println("Connected to the database");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
```
此代码段将连接到名为“library”的MySQL数据库,并使用用户名“root”和密码“password”。
接下来,您需要编写一个Java方法来向数据库添加新书籍。以下是一个示例方法:
```java
import java.sql.*;
public class AddBook {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "password");
String title = "Java Programming";
String author = "John Smith";
String isbn = "978-0134685991";
PreparedStatement stmt = con.prepareStatement("INSERT INTO books (title, author, isbn) VALUES (?, ?, ?)");
stmt.setString(1, title);
stmt.setString(2, author);
stmt.setString(3, isbn);
int rowsInserted = stmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new book was inserted successfully!");
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
```
此代码将在名为“books”的MySQL表中添加一本新书。您可以根据需要修改标题,作者和ISBN号。PreparedStatement对象用于防止SQL注入攻击。
希望这可以帮助您开始编写Java代码来连接MySQL数据库并添加新书籍。