简体   繁体   中英

Why createStatement method is declared under Connection Interface instead of Statement interface?

I'm going through one big doubt. Today I was practicing database connection and reading records from table in MySQL database. Everything worked fine.

While coding I came across two Interfaces, one Connection and second is Statement. After setting up a connection using below code snippet .

Connection Con = DriverManager.getConnection(host, username, password);

I had to create an Statement object which will be used for executing SQL query. So I did like this and was able to get records.

Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );

My Question is, If Statement object is required most of the time then why createStatement() is declared in Connection interface. Why it was not declared under Statement interface? Is there is any specific reason which I'm really not aware of?

At the end, below code is being used to get an Statement reference to object which is implemented by StatementImpl .

public class ConnectionImpl
  extends ConnectionPropertiesImpl
  implements Connection
{...

public Statement createStatement()
    throws SQLException
  {
    return createStatement(1003, 1007);
  }

  public Statement createStatement(int resultSetType, int resultSetConcurrency)
    throws SQLException
  {
    checkClosed();

    StatementImpl stmt = new StatementImpl(this, this.database);
    stmt.setResultSetType(resultSetType);
    stmt.setResultSetConcurrency(resultSetConcurrency);

    return stmt;
  }


}

The createStatement() method is not static. It relies on Connection data. If method was created as static in Statement interface, it would need to ask for Connection instance as input parameter.

Different Connection implementations might instantiate Statements in different ways (and with different implementations).

So it was decided to be part of the Connection responsibility to instantiate one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM