Execute Method (SqlStatement)
On this page
Executes the statement and returns result set.
Syntax
Return Value
Result set returned by the statement execution.
Example
This sample shows how to retrieve collection of statements that make up the script and execute them one by one.
|
|---|
string script =
"INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');"+
"INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');"+
"INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');"+
"INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');"+
"SELECT * FROM DEPT";
SqlConnection myConn = new SqlConnection(
"User Id=sa;Server=localhost;Initial Catalog=Test;");
SqlScript myScript = new SqlScript(script,myConn);
SqlStatementCollection myColl = myScript.Statements;
IDataReader myReader;
myConn.Open();
foreach (SqlStatement myStatement in myColl)
{
Console.WriteLine(myStatement.Text);
try
{
myReader = myStatement.Execute();
Console.WriteLine(" Records affected " + myReader.RecordsAffected);
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
Console.WriteLine();
}
catch
{
Console.WriteLine(" Failed");
}
}
myConn.Close(); |
|
|---|
Dim script As String = _
"INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');" + _
"INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');" + _
"INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');" + _
"INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');" + _
"SELECT * FROM DEPT"
Dim myConn As SqlConnection = New SqlConnection( _
"User Id=sa;Server=localhost;Initial Catalog=Test;")
Dim myScript As SqlScript = New SqlScript(script, myConn)
Dim myColl As SqlStatementCollection = myScript.Statements
Dim myReader As IDataReader
myConn.Open()
For Each myStatement As SqlStatement In myColl
Console.WriteLine(myStatement.Text)
Try
myReader = myStatement.Execute()
Console.WriteLine(" Records affected " & myReader.RecordsAffected)
While myReader.Read()
Console.WriteLine(myReader.GetString(0))
End While
myReader.Close()
Console.WriteLine()
Catch ex As Exception
Console.WriteLine(" Failed")
End Try
Next myStatement
myConn.Close() |
See Also