Is There Any Difference Between SqlConnection.CreateCommand and new SqlCommand?

前端 未结 4 1542
灰色年华
灰色年华 2020-12-08 14:22

In .Net, is there any functional difference between creating a new SqlCommand object and attaching a SqlConnection to it and calling CreateCo

相关标签:
4条回答
  • 2020-12-08 14:38

    This may go without saying, but just to be complete, there is one difference. If you create a SqlCommand, you can pass in the CommandText as a parameter. If you let the SqlConnection CreateCommand, there is no provision for supplying the CommandText. Since you can just set the SqlCommand's CommandText property, the distinction is pretty slim, but it does exist.

    SqlConnection db = new SqlConnection();
    SqlCommand cmd = db.CreateCommand();
    cmd.CommandText = "select @@version";
    

    or

    SqlConnection db = new SqlConnection();
    SqlCommand cmd = new SqlCommand("select @@version", db);
    
    0 讨论(0)
  • 2020-12-08 14:41

    Functionally they are exactly the same.

    However, SqlConnection.CreateCommand() lets you be more agnostic about what type of DB you are using. For example instead of passing a SqlConnection instance around you could pass it around as a DbConnection which would yield a DbCommand.

    0 讨论(0)
  • 2020-12-08 14:52

    They do the same thing. The rationale behind SqlConnection.CreateCommand is to implement the factory pattern.

    0 讨论(0)
  • 2020-12-08 14:56

    No, they are the same thing.

    I disassembled SqlConnection.CreateCommand and found this:

    public SqlCommand CreateCommand()
    {
            return new SqlCommand(null, this);
    }
    

    which proves that they really are the same thing.

    0 讨论(0)
提交回复
热议问题