Tuesday, August 23, 2011

On DbCommand, ExecuteReader, ExecuteScalar, etc and creating database through ADO.NET

Ideally we run a DML query in ExecuteNonQuery.
What will happen when a DML query is run in ExecuteReader,ExecuteScalar,or ExecuteXmlReader  ?

No Exception is thrown, RecordsAffected contains the number of records affected.
HasRows returns false, .Read returns false, RecordsAffected contains number of records afftected.
When read is attempted, error "Invalid attempt to read when no data is present" is thrown

No Exception is thrown, query is executed, however NULL object is returned,
Returns the first column of first row, is not found returns null ( null object).
When the return value is actually null, DBNull.Value is returned.

InvalidOperationException is thrown , however, query is executed before throwing an exception.
        "Invalid command sent to ExecuteXmlReader.  The command must return an Xml result."   

Another interesting question :
Can you create database and other objects using the DbCommand objects?
But you cannot immediaately switch to the database because you cannot use GO statements in
DbCommand command texts, so you need to change the connection string to change 'Initial Catalog' name
and then issue rest of commands.

What are the attributes of connection string ?

Data Source : Name/IP of the server
Initial Catalog : Name of the database
User ID  : User id
Password : user password
Persist Secutiry Info : True by default.

No comments:

Post a Comment