October 14, 2002 - The SqlConnection Class
October 14, 2002 The SqlConnection Class Tips: October 2002
Yehuda Shiran, Ph.D.
|
SqlConnection
object. You need to create an instance of SqlConnection
, call its Open()
method, read the records with an SqlCommand
instance object, and then close the connection by either passing the constant CommandBehavior.CloseConnection
to the SqlCommand
instance object, or by calling the SqlConnection
's Close()
method.
The constructor of the SqlConnection
object expects one parameter: the connection string. The connection string identifies the SQL server name, the SQL database name, and satisfies the authorization requirement by providing a user name and a password, or by specifying Trusted_Connection=true
. You can specify the connection string in line within the constructor line, or you can specify it in Web.config
. In IBuySpy, it is defined in Web.config
as follows:
<add key="ConnectionString"
value="server=HAW2L1800\NetSDK;Trusted_Connection=true;database=StoreDOCJS" />
Here is the constructor line repeated by each and every method of the five JScript .NET modules:
var myConnection : SqlConnection =
new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
Here is how we open the connection, retrieve records from the database, and close the connection:
myConnection.Open();
var result : SqlDataReader =
myCommand.ExecuteReader(CommandBehavior.CloseConnection);
And here is how we open the connection, retrieve some parameters (as opposed to records), and close the connection:
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();