PreparedStatement stmt = conn.prepareStatement("INSERT INTO books (book_name, book_price, book_author, book_description, category_id) VALUES (?, ?, ?, ?, ?)"); stmt.setString(1, bookName); stmt.setDouble(2, bookPrice); stmt.setString(3, bookAuthor); stmt.setString(4, bookDescription); stmt.setInt(5, categoryId); stmt.executeUpdate(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
时间: 2024-02-14 08:18:46 浏览: 19
这段代码是使用Java语言和JDBC API将书籍信息插入到数据库中的示例。预编译语句PreparedStatement可以防止SQL注入攻击,并且可以提高查询效率。在这个示例中,我们首先使用conn.prepareStatement方法创建一个预编译语句对象,然后使用setXXX方法设置参数值,其中XXX代表参数类型。在这个示例中,我们使用了setString、setDouble和setInt方法分别设置书名、价格、作者、描述和分类ID参数的值。最后,我们使用stmt.executeUpdate方法执行插入操作,并在最后关闭相关资源。如果发生异常,我们使用e.printStackTrace方法打印异常信息。在finally块中,我们关闭数据库连接,以释放资源并避免资源泄漏。
相关问题
假定已经获得一个数据库连接,使用变量conn来表示。下列语句中能够正确获得结果集的有__1__。(选择两项) A.Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT * FROM STUDENT”); B.Statement stmt = conn.createStatement(“SELECT * FROM STUDENT”); ResultSet rs = stmt.executeQuery(); C.PreparedStatement stmt = conn.prepareStatement(); ResultSet rs = stmt.executeQuery(“SELECT * FROM STUDENT”); D.PreparedStatement stmt = conn.prepareStatement(“SELECT * FROM STUDENT”); ResultSet rs = stmt.executeQuery();
正确答案是 A 和 D。
A 中的语句使用了 `conn.createStatement()` 创建 Statement 对象,并将 SQL 查询语句作为参数传递给 `executeQuery()` 方法,可以正确获得结果集。
D 中的语句使用了 `conn.prepareStatement()` 创建 PreparedStatement 对象,并在创建时传递了 SQL 查询语句作为参数,然后调用 `executeQuery()` 方法,也可以正确获得结果集。
B 中的语句使用了错误的函数调用方式,应该先调用 `conn.createStatement()` 创建 Statement 对象,再传递 SQL 查询语句作为参数给 `executeQuery()` 方法。
C 中的语句创建了一个 PreparedStatement 对象,但是没有传递 SQL 查询语句,因此无法正确获得结果集。
String sql = "SELECT * FROM articles WHERE title LIKE ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, "%" + keyword + "%"); ResultSet rs = stmt.executeQuery();使用这段代码进行模糊查找时无法查找中文
可能是因为数据库的字符集不支持中文,可以尝试修改数据库的字符集为 utf8mb4。同时,在代码中也需要指定字符集为 utf8mb4,可以在连接数据库时加上以下语句:?useUnicode=true&characterEncoding=utf8mb4。修改后的代码如下:
String sql = "SELECT * FROM articles WHERE title LIKE ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + keyword + "%");
ResultSet rs = stmt.executeQuery();
rs.close();
stmt.close();
conn.close();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8mb4", "username", "password");