有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从语句创建PreparedStatement?

这听起来有点奇怪,但我想创建一个PreparedStatement
在我有一个Statement之后。这是因为我的项目几乎是50%,直到现在 我用了Statement

在我的数据库类中,每当我需要使用mysql服务器时,我都有一个连接到mysql的构造函数:

public class Database 
{
    private Statement m_statement = null;
    private Connection m_connection = null;
    private PreparedStatement m_prepared = null;  // that one was added just now 

    private static final String ACCOUNTS_TABLE = "CheckingAccountsTable";
    private static final String PERSONNEL_TABLE = "PersonnelTable";
    // private static final String 


    public Database() throws ClassNotFoundException
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            this.m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");
            this.m_statement = this.m_connection.createStatement();

        }

        catch (SQLException s)
        {
            System.out.println("SQL statement is not executed! 2!");
        }

    }


}




// from here I have something like 20 methods that are based on the Statement

改变一切都需要很多我没有的时间。所以,我的问题是:

我可以使用我用PreparedStatement创建的语句吗?或者基于Statement创建PreparedStatement

谢谢


共 (1) 个答案

  1. # 1 楼答案

    这是不可能的StatementPreparedStatement代表不同的事物

    • Statement用于调用不同的SQL查询,您可以创建一个Statement实例,而不知道要使用什么SQL查询
    • PreparedStatement在创建时会得到一个SQL查询,如果可能,驱动程序会尝试预编译该查询。可以填写不同的参数并重复使用,但不能更改查询,它始终使用创建时给定的参数

    所以我担心你必须重构你的代码,没有简单的方法可以在这两者之间切换

    在大多数情况下,最好使用PreparedStatement,因为它允许您以安全的方式将参数传递给SQL查询,而不会冒SQL injection的风险