ADO Command
The Command
object in ADO is used to execute SQL statements, stored procedures, or other commands on a database. It provides flexibility in managing complex database operations.
Key Topics
Executing SQL Commands
Example
<%
Dim conn, cmd
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=myUser;Password=myPassword;"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = "INSERT INTO Employees (EmployeeName, Department) VALUES ('John Doe', 'IT')"
cmd.Execute
Response.Write("SQL command executed successfully.")
conn.Close
Set cmd = Nothing
Set conn = Nothing
%>
Explanation: This example demonstrates how to execute an INSERT
SQL command using the Command
object.
Executing Stored Procedures
Example
<%
Dim conn, cmd
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=myUser;Password=myPassword;"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = "usp_AddEmployee"
cmd.CommandType = 4 ' Stored Procedure
cmd.Parameters.Append cmd.CreateParameter("@EmployeeName", 200, 1, 50, "Jane Smith")
cmd.Parameters.Append cmd.CreateParameter("@Department", 200, 1, 50, "Finance")
cmd.Execute
Response.Write("Stored procedure executed successfully.")
conn.Close
Set cmd = Nothing
Set conn = Nothing
%>
Explanation: This example demonstrates executing a stored procedure with parameters using the Command
object.
Key Takeaways
- Use the
Command
object to execute SQL commands and stored procedures. - Parameters enhance security and flexibility in command execution.
- Command objects provide robust control over database interactions.