There are lots of different ways to accomplish this: Dynamic Data, LinqToSQL, Typed data sets, Data Access Application Block, or another ORM. My preferred method is direct sql, which would use code something like this:
Public Sub SaveAnswer(ByVal answer As String)
Dim sql As String = "INSERT INTO [table1] (ans) VALUES (@Answer)"
Using cn As New SqlConnection(getConnectionString()), _
cmd As New SqlCommand(sql)
cmd.Parameters.Add("@Answer", SqlDbType.VarChar, 50).Value = answer
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Private Function getConnectionString() As String
''//normally read from a config file for this
Return "Server=(local)\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"
End Function
A few things to take from this sample:
- It properly closes the db connection, even if an exception is thrown, via the
Using
block
- Parameterized query to prevent sql injection
getConnectionString()
is private. You should abstract out your data access to a separate class or assembly, and this is one way to start enforcing that.