Represents an open connection to SQL Server.
The following example creates a
SqlCommand and a
SqlConnection. The
SqlConnection is opened and set as the
Connection property. The example then calls
ExecuteNonQuery method, and closes the connection. To accomplish this, the
ExecuteNonQuery is passed a connection string and a query string that is SQL INSERT statement.
|
|---|
public void InsertRow(string sqlConnectionString)
{
// If the connection string is empty, use default.
if(sqlConnectionString == "")
{
sqlConnectionString =
"User Id=sa;Server=localhost;Initial Catalog=Test;";
}
SqlConnection myConn = new SqlConnection(sqlConnectionString);
string myInsertQuery = "INSERT INTO DEPT VALUES (50,'Development','Philadelphia')";
SqlCommand sqlCommand = new SqlCommand(myInsertQuery);
sqlCommand.Connection = myConn;
myConn.Open();
try
{
sqlCommand.ExecuteNonQuery();
}
finally
{
myConn.Close();
}
} |
|
|---|
Public Sub InsertRow(sqlConnectionString As String)
' If the connection string is empty, use default.
If sqlConnectionString = "" Then
sqlConnectionString = _
"User Id=sa;Server=localhost;Initial Catalog=Test;"
End If
Dim myConn As New SqlConnection(sqlConnectionString)
Dim myInsertQuery As String = "INSERT INTO DEPT VALUES (50,'Development','Philadelphia')"
Dim sqlCommand As New SqlCommand(myInsertQuery)
sqlCommand.Connection = myConn
myConn.Open()
Try
sqlCommand.ExecuteNonQuery()
Finally
myConn.Close()
End Try
End Sub |