开发者

preparedStatement.setString taking over 5 seconds longer then hardcoding parameters

I am connecting to a Microsoft sql server database via java jdbc and having a very strange issue. Whenever I use the place holder parameters (?) in my query in the where clause and then do preparedStatement.setString(..) method my simple query takes anywhere from 4800 to 5800 milliseconds to run. When I hardcode the where clause inside of the query itself, it takes from 1 to 36 milliseconds to run. This doesn't make sense to me, because I thought using the placeholders was supposed to be faster...

The table does have a lot of rows (8 million or so), however the parameters that I pass in are just a few characters, I only pass in 2 parameters, the statement always returns 1 (or 0) rows and the data it returns is not huge. Indexes on the table don't help. Why such a HUGE time difference? 5-6 seconds is a really long time for such a query. Both of the columns in the where clause are string-type (varchar(20)) so there is no implicit type conversion on the databse side (that I know of).

I've tried a different version of the sqljdbc4.jar driver, but it's doing the same thing.

package testdbconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) throws SQLException 
    {
        Connection con = getConnection();

        PreparedStatement statement = con.prepareStatement("select col1 from tableName where username = ? and password = ?");

        statement.setString(1, "UName");
        statement.setString(2, "PWord");

        long 开发者_如何学JAVAstart = System.currentTimeMillis();

        ResultSet rs = statement.executeQuery();

        long stop = System.currentTimeMillis();

        System.out.println("took: " + (stop - start));

        rs.close();
        con.close();

    }// end main

    private static Connection getConnection()
    {
        Connection connection = null;

        try {
            // Load the JDBC driver
            String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
            Class.forName(driverName);

            // Create a connection to the database
            String url = "jdbc:sqlserver://DBSERVERNAME;databaseName=DBNAME;";
            String username = "dbUname";
            String password = "dbPword";

            connection = DriverManager.getConnection(url, username, password);
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (SQLException e) 
        {
            e.printStackTrace();
        }

        return connection;
    }// end getConnection()

}

Output: run: took: 4891 BUILD SUCCESSFUL (total time: 5 seconds)

Now if I do this:

package testdbconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) throws SQLException 
    {
        Connection con = getConnection();

        PreparedStatement statement = con.prepareStatement("select col1 from tableName where username = 'UName' and password = 'PWord'");

        long start = System.currentTimeMillis();

        ResultSet rs = statement.executeQuery();

        long stop = System.currentTimeMillis();

        System.out.println("took: " + (stop - start));

        rs.close();
        con.close();

    }// end main

    private static Connection getConnection()
    {
        Connection connection = null;

        try {
            // Load the JDBC driver
            String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
            Class.forName(driverName);

            // Create a connection to the database
            String url = "jdbc:sqlserver://DBSERVERNAME;databaseName=DBNAME;";
            String username = "dbUname";
            String password = "dbPword";

            connection = DriverManager.getConnection(url, username, password);
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (SQLException e) 
        {
            e.printStackTrace();
        }

        return connection;
    }// end getConnection()

}

Output: run: took: 32 BUILD SUCCESSFUL (total time: 2 seconds)


Generally speaking, running an entirely hardcoded statement will be faster than an equivalent parameterized statement. The reason for this has to do with the execution planning of the database. When you provide all of the information from the start, the database can perform optimizations and choose shorter paths specific to the exact data you provided. When you parameterize the statement, it can only perform those optimizations that would be helpful for any value that might be inserted.

Parameterized statements can be helpful when you need to run many similar queries and want to avoid the overhead of preparing the statement every time, but for a single query on a large data set (as in your use case) a hardcoded query will be better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜