java代码新建一个表格book(书号,书名,作者,价格,出版社,书类),新增三条记录,用jdbc连接
时间: 2024-03-03 09:49:44 浏览: 75
java+JDBC+mysql 图书管理系统 实现了 图书的查询 修改 新增 删除等
好的,以下是示例代码:
```java
import java.sql.*;
public class BookTableExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/example";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// 创建表格
String createSql = "CREATE TABLE book ("
+ "id INT NOT NULL AUTO_INCREMENT,"
+ "book_number VARCHAR(20) NOT NULL,"
+ "book_name VARCHAR(50) NOT NULL,"
+ "author VARCHAR(50) NOT NULL,"
+ "price DOUBLE NOT NULL,"
+ "publisher VARCHAR(50) NOT NULL,"
+ "book_type VARCHAR(20) NOT NULL,"
+ "PRIMARY KEY (id))";
stmt.executeUpdate(createSql);
// 新增记录
String insertSql1 = "INSERT INTO book (book_number, book_name, author, price, publisher, book_type) VALUES ('001', 'Java入门', '张三', 28.5, '出版社A', '计算机类')";
String insertSql2 = "INSERT INTO book (book_number, book_name, author, price, publisher, book_type) VALUES ('002', 'Python基础', '李四', 35.0, '出版社B', '计算机类')";
String insertSql3 = "INSERT INTO book (book_number, book_name, author, price, publisher, book_type) VALUES ('003', '数据结构与算法', '王五', 42.0, '出版社C', '计算机类')";
stmt.executeUpdate(insertSql1);
stmt.executeUpdate(insertSql2);
stmt.executeUpdate(insertSql3);
// 打印新增记录
String selectSql = "SELECT * FROM book";
ResultSet rs = stmt.executeQuery(selectSql);
while(rs.next()){
int id = rs.getInt("id");
String bookNumber = rs.getString("book_number");
String bookName = rs.getString("book_name");
String author = rs.getString("author");
double price = rs.getDouble("price");
String publisher = rs.getString("publisher");
String bookType = rs.getString("book_type");
System.out.println("id: " + id + ", book_number: " + bookNumber + ", book_name: " + bookName + ", author: " + author + ", price: " + price + ", publisher: " + publisher + ", book_type: " + bookType);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
} catch (SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
```
请注意,以上代码中的数据库连接信息和表结构都需要根据实际情况进行修改,否则无法正确执行。
阅读全文