且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL语法错误尝试将行插入表时出现异常

更新时间:2023-01-22 14:12:16

代码中的两个问题:


  1. SQL语句不需要分号 ; 结尾。它会使代码失败。

  1. SQL statements don't need semicolon ; at the end. It will make the code fail.

代码很容易出现SQL注入,很难维护。改为使用 PreparedStatement

The code is prone to SQL Injection and is hard to maintain. Use a PreparedStatement instead:

这应该是有效的代码:

String sql = "INSERT INTO MyAlbums VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
if(album instanceof CDAlbum) {
    pstmt.setString(1, "CD");
    CDAlbum cdAlbum = (CDAlbum)album;
    pstmt.setString(4, cdAlbum.getArtist());
    pstmt.setString(5, cdAlbum.getTracks());
}
if(album instanceof DVDAlbum) {
    pstmt.setString(1, "DVD");
    DVDAlbum dvdAlbum = (DVDAlbum)album;
    pstmt.setString(4, dvdAlbum.getDirector());
    pstmt.setString(5, dvdAlbum.getPlotOutline());
}
pstmt.setString(2, album.getTitle());
pstmt.setString(3, album.getGenre());
pstmt.executeUpdate();

普通字符串连接与此方法之间的区别是 PreparedStatement 参数将转义任何'等你的角色。

The big difference between plain string concatenation and this approach for your case is that PreparedStatement parameters will escape any ' and " and other characters for you.