Skip to content
Advertisement

How to edit and delete rows of a database using ASP?

I currently have a website that displays all the data within the database

        Dim dcSQL As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("College").ConnectionString)
        Dim dbAdapt As New System.Data.SqlClient.SqlDataAdapter()
        Dim cmd As New SqlCommand("SELECT * FROM [College].[dbo].[Class]", dcSQL)
        dbAdapt.SelectCommand = cmd


        Dim ds As New DataSet
        dbAdapt.Fill(ds)

        If dbAdapt IsNot Nothing Then
            gvStudents0.DataSource = ds.Tables(0)
            gvStudents0.DataBind()
        End If
    Catch ex As Exception

    End Try
End Sub'

But I want to create/edit and delete the database, I am aware of how to do this in EF but I am currently not aware in SQL, can someone help?

Advertisement

Answer

The following snippet is from SqlCommand.Parameters Property .

Updating

    Dim commandText As String = _
     "UPDATE Sales.Store SET Demographics = @demographics " _
     & "WHERE CustomerID = @ID;"

    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(commandText, connection)

        ' Add CustomerID parameter for WHERE clause.
        command.Parameters.Add("@ID", SqlDbType.Int)
        command.Parameters("@ID").Value = customerID

        ' Use AddWithValue to assign Demographics.
        ' SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml)

        Try
            connection.Open()
            Dim rowsAffected As Integer = command.ExecuteNonQuery()
            Console.WriteLine("RowsAffected: {0}", rowsAffected)

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Using 

Deleting

For deleting the command could be as follows.

Dim commandText As String = _
     "DELETE FROM Sales.Store WHERE CustomerID = @ID;"

(...)

command.Parameters.Add("@CustomerID ", SqlDbType.Int).Value = xxx;

Inserting

For inserting the sql will be something like the following

Dim commandText As String = _
     "INSERT INTO tablename(column1,column2,column3)" _
     & " VALUES(@column1,@column2,@column3);"

and then

command.Parameters.Add("@column1", SqlDbType.Int).Value = x;
command.Parameters.Add("@column2", SqlDbType.Int).Value = y;
command.Parameters.Add("@column3", SqlDbType.Int).Value = z;

or

command.Parameters.AddWithValue("@column1", x);
command.Parameters.AddWithValue("@column2", y);
command.Parameters.AddWithValue("@column3", z)

Please note that this is not ASP.NET specific. A console app could use this code as well.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement