📜  如何在Java中使用 PreparedStatement?

📅  最后修改于: 2022-05-13 01:55:27.584000             🧑  作者: Mango

如何在Java中使用 PreparedStatement?

PreparedStatement是预编译的 SQL 语句。它是Statement的子接口。与 Statement 对象相比,Prepared Statement 对象具有一些有用的附加功能。 PreparedStatement 对象提供了执行参数化查询的功能,而不是硬编码查询。

PreparedStatement 的优点

  • 在创建 PreparedStatement 时,SQL 查询作为参数传递。这个 Prepared Statement 包含一个预编译的 SQL 查询,所以当 PreparedStatement 被执行时,DBMS 可以直接运行查询而不是先编译它。
  • 我们可以使用相同的 PreparedStatement 并在执行时提供不同的参数。
  • PreparedStatements 的一个重要优点是它们可以防止 SQL 注入攻击。

使用 PreparedStatement 的步骤

1. 创建到数据库的连接

Connection myCon = DriverManager.getConnection(path,username,password)

2. 准备声明
而不是像这样的硬编码查询,

select * from students where age>10 and name ='Chhavi'

设置参数占位符(占位符使用问号),例如,

select * from students where age> ? and name = ?
PreparedStatement myStmt; 
myStmt = myCon.prepareStatement(select * from students where age> ? and name = ?);

3. 设置类型和位置的参数值

myStmt.setInt(1,10);     
myStmt.setString(2,"Chhavi");      

4. 执行查询

ResultSet myRs= myStmt.executeQuery();  

PreparedStatement的方法:

  • setInt(int, int):此方法可用于在给定参数索引处设置整数值。
  • setString(int, 字符串):此方法可用于在给定的参数索引处设置字符串值。
  • setFloat(int, float):此方法可用于在给定的参数索引处设置浮点值。
  • setDouble(int, double):此方法可用于在给定的参数索引处设置双精度值。
  • executeUpdate():此方法可用于创建、删除、插入、更新、删除等。它返回 int 类型。
  • executeQuery():它在执行选择查询时返回 ResultSet 的实例。
初始表内容

原表

执行查询示例代码

Java
// Java program to execute a query using PreparedStatement
 
import java.sql.*;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args) throws Exception
    {
 
        // Register Driver Class
        Class.forName("org.apache.derby.jdbc.ClientDriver");
 
        // Connection to your database
        Connection con = DriverManager.getConnection();
 
        // Query which needs parameters
        String query
            = "Select * from students where age> ? and name = ?";
 
        // Prepare Statement
        PreparedStatement myStmt
            = con.prepareStatement(query);
 
        // Set Parameters
        myStmt.setInt(1, 20);
        myStmt.setStrin(2, 'Prateek');
 
        // Execute SQL query
        ResultSet myRs = myStmt.executeQuery();
 
        System.out.println('Age      Name');
 
        // Display function to show the Resultset
        while (myRs.next()) {
            String Name = rs.getString("name");
            int age = rs.getInt("age");
            System.out.println(Name + "     " + age);
        }
 
        // Close the connection
        con.close();
    }
}


Java
// Java program to update a table using PreparedStatement
 
import java.sql.*;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args) throws Exception
    {
 
        // Register Driver Class
        Class.forName("org.apache.derby.jdbc.ClientDriver");
 
        // Connection to your database
        Connection con = DriverManager.getConnection();
 
        // Query which needs parameters
        String query = "insert into Students values(?,?)";
 
        // Prepare Statement
        PreparedStatement myStmt
            = con.prepareStatement(query);
 
        // Set Parameters
        myStmt.setInt(1, 21);
        myStmt.setStrin(2, 'Prajjwal');
 
        // Execute SQL query
        int res = myStmt.executeUpdate();
 
        // Display the records inserted
        System.out.println(res + " records inserted");
 
        // Close the connection
        con.close();
    }
}



使用preparedstatement执行查询

输出

执行更新示例代码

Java

// Java program to update a table using PreparedStatement
 
import java.sql.*;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args) throws Exception
    {
 
        // Register Driver Class
        Class.forName("org.apache.derby.jdbc.ClientDriver");
 
        // Connection to your database
        Connection con = DriverManager.getConnection();
 
        // Query which needs parameters
        String query = "insert into Students values(?,?)";
 
        // Prepare Statement
        PreparedStatement myStmt
            = con.prepareStatement(query);
 
        // Set Parameters
        myStmt.setInt(1, 21);
        myStmt.setStrin(2, 'Prajjwal');
 
        // Execute SQL query
        int res = myStmt.executeUpdate();
 
        // Display the records inserted
        System.out.println(res + " records inserted");
 
        // Close the connection
        con.close();
    }
}


使用 PreparedStatement 查询更新表

输出

更新后的表格内容

插入值后的表格