How can ASP language interact with SQL Server database?
To utilize ASP language for operating on a SQL Server database, you can establish a connection and perform operations using ADO (ActiveX Data Objects). Below is a simple example code:
- Connect to the database.
<%
Dim conn
Set conn = Server.CreateObject("ADODB.Connection")
Dim connStr
connStr = "Provider=SQLOLEDB;Data Source=your_server_name;Initial Catalog=your_database_name;User ID=your_user_name;Password=your_password;"
conn.Open connStr
%>
- Execute a search and retrieve data:
<%
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM your_table", conn
If Not rs.EOF Then
Do While Not rs.EOF
Response.Write rs("column_name") & "<br>"
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
%>
- Inserting data:
<%
Dim sql
sql = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')"
conn.Execute sql
%>
- Update Data:
<%
Dim sql
sql = "UPDATE your_table SET column1 = 'new_value' WHERE column2 = 'value'"
conn.Execute sql
%>
- Delete Data
<%
Dim sql
sql = "DELETE FROM your_table WHERE column = 'value'"
conn.Execute sql
%>
In actual development, more complex SQL statements and operations can be written based on specific needs and business logic. It is also important to consider the security of database connections and performance optimization.