insert into foodDB(typeId,typeName,price) values(?,?,?)java
时间: 2024-10-21 11:12:24 浏览: 19
在Java中,如果你想要向名为foodDB的数据库表中插入数据,通常你会使用JDBC(Java Database Connectivity)或者ORM框架如MyBatis、Hibernate等。假设你正在使用基本的JDBC操作,你可以创建一个PreparedStatement来防止SQL注入,并执行以下代码:
```java
String sql = "INSERT INTO foodDB (typeId, typeName, price) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase", "username", "password");
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// 设置参数值
pstmt.setInt(1, typeId); // 替换为实际的typeid值
pstmt.setString(2, typeName); // 替换为实际的typeName值
pstmt.setDouble(3, price); // 替换为实际的price值
// 执行插入操作
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Data inserted successfully.");
} else {
System.out.println("Failed to insert data.");
}
} catch (SQLException e) {
e.printStackTrace();
}
```
阅读全文