尝试将产品插入访问数据库时,我收到许多不同的错误。例如格式错误的字符串:)。用户权限不足或找不到对象。当我尝试插入不同的产品时出现不同的错误。
尝试重新创建数据库,调试至快捷键。
公共布尔addNewProduct(产品产品) {
String Make = "";
String Model = "";
String Type = "";
String Genre = "";
String AttConsole = "";
String Desc = "";
if(product.getClass().getName().equals("Models.Game"))
{
Game game = (Game)product;
Genre = String.valueOf(game.getGenre());
AttConsole = String.valueOf(game.getAttributedConsole());
Desc = String.valueOf(game.getDescription());
}
else if(product.getClass().getName().equals("Models.Console"))
{
Console console = (Console)product;
Make = String.valueOf(console.getMake());
Model = String.valueOf(console.getModel());
Desc = String.valueOf(console.getDescription());
}
else
{
Peripheral peripheral = (Peripheral)product;
Type = String.valueOf(peripheral.getType());
Desc = String.valueOf(peripheral.getDescription());
}
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO Products (ProductName, Price, StockLevel, Description, Genre, AttributedConsole, Make, Model, Type) VALUES "
+ "('" + product.getProductName() + "','" + product.getPrice() + "','" + product.getStocklevel()
+ "','" + Desc + "','" + Genre + "','" + AttConsole +
"','" + Make + "','" + Model + "'," + Type + ")");
//sql statement to add new products to database
conn.close();
return true;
}
catch(Exception ex)
{
String message = ex.getMessage();
return false;
}
}
ex =(net.ucanaccess.jdbc.UcanaccessSQLException)net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc ::: 4.0.4意外令牌:) 例如=(net.ucanaccess.jdbc.UcanaccessSQLException)net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc :::: 4.0.4用户缺少特权或找不到对象:RAZOR
答案 0 :(得分:0)
请勿使用字符串串联将列值插入SQL命令文本中。搜索“ SQL注入”或“小鲍比表”以获取有关为什么这是“坏东西”™的更多信息。
相反,请使用PreparedStatement
来运行参数化查询,例如
String sql = "INSERT INTO tableName (intColumn, textColumn) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 12345);
ps.setString(2, "my text value");
ps.executeUpdate();
}