在 vb.net 中编写 sql 代码 [英] writing sql code in vb.net
问题描述
我在 ASP.net 3.5 页面的文本框中输入了信息.当我单击提交按钮时,我希望将此信息写入 sql server 数据库.
I have information entered into a text box on an ASP.net 3.5 page. when i click the submit button i would like this information written to a sql server database.
有人可以告诉我我需要做什么来完成这个任务吗?最终用户不应看到任何东西.
Can someone please tell me what I need to do to accomplish this. The end-user should not see anything.
我使用的是visual web developer 2008.事件处理代码使用vb放在一个单独的文件中.
I am using visual web developer 2008. the event handling code is placed in a separate file using vb.
谢谢.
推荐答案
有很多不同的方法来实现这一点:动态数据、LinqToSQL、类型化数据集、数据访问应用程序块或其他ORM.我的首选方法是直接 sql,它会使用如下代码:
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:
- 它通过
Using
块 正确关闭数据库连接,即使抛出异常 - 参数化查询以防止 sql 注入
getConnectionString()
是私有的.您应该将数据访问抽象到一个单独的类或程序集,这是开始强制执行的一种方法.
- 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.
这篇关于在 vb.net 中编写 sql 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!