从我的文本框将值传递给SQL查询参数 [英] Passing value to SQL query parameter from my textbox

查看:130
本文介绍了从我的文本框将值传递给SQL查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用以下代码连接到我的数据库.

Hi,
I am using following code to connect to my database.

<pre lang="vb"> Dim conStr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\dbTest.mdf;Integrated Security=True;User Instance=True"
     Dim sqlQry As String = "SELECT * FROM [tblTest] WHERE ([Name] = @Name)"
       Dim dAdt As New SqlDataAdapter(sqlQry, conStr)
    Dim dSet As New DataSet()



然后用
填充适配器



Then filling adapter with

<pre lang="vb">dAdt.Fill(dSet, "tblTest")


然后我可以按照自己想要的方式使用数据.

我的问题是:
如何通过文本框传递用户将给出的参数值.


and then I can use the data the way I want.

My question is:
How to pass the value of parameter that user will give through a text box.

Dim sqlQry As String = "SELECT * FROM [tblTest] WHERE ([Name] = @Name)

"

我的意思是如何将参数值传递给我的查询?
请修改我的代码以告诉我该怎么做.
非常感谢.

"

I mean how to pass the parameter value to my query?
Please modify my code to tell me how to do it.
Thanks a lot.

推荐答案

有两种方法:

解决方案1:
There are two ways to do so :

Solution 1 :
Dim sqlQry As String = "SELECT * FROM [tblTest] WHERE [Name] = " + textBox1.text



解决方案2:



Solution 2 :

Dim sqlQry As String = "SELECT * FROM [tblTest] WHERE [Name] = @Name"

Dim command As New SqlCommand(sqlQry, connection)

'' Add Name parameter for WHERE clause.
command.Parameters.Add("@Name", SqlDbType.Varchar, 20) -- 20 Refers to the size
command.Parameters("@Name").Value = textBox1.Text



希望这会有所帮助.
一切顺利.



Hope this helps.
All the best.


请参阅此处: http://vbnetsample.blogspot.com/2007/10/using-sqlparameter-class.html [ ^ ]


使用参数(这正是您应该做的),您应该定义一个SqlCommand对象分别使用该命令作为您的数据适配器.因此整个代码可能类似于:
When you use parameters (and that''s exactly what you should do) you should define a SqlCommand object separately and use that command for your data adapter. So the whole code could look something like:
Dim conStr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\dbTest.mdf;Integrated Security=True;User Instance=True"
Dim sqlQry As String = "SELECT * FROM [tblTest] WHERE ([Name] = @Name)"
Dim dAdt As New System.Data.SqlClient.SqlDataAdapter()
Dim dSet As New DataSet()
Dim queryCommand As New System.Data.SqlClient.SqlCommand()
Dim queryConnection As New System.Data.SqlClient.SqlConnection()

queryConnection.ConnectionString = conStr
queryConnection.Open()
queryCommand.Connection = queryConnection
queryCommand.CommandText = sqlQry
queryCommand.Parameters.AddWithValue("@Name", textBox1.Text)
dAdt.SelectCommand = queryCommand
dAdt.Fill(dSet)
queryConnection.Close()


请记住将textBox1.Text替换为实际的文本框对象.

另外,打开连接,执行填充等也应包含在适当的try..catch块


Remember to replace textBox1.Text with your actual text box object.

Also opening the connection, executing the fill etc should be enclosed to proper try..catch block


这篇关于从我的文本框将值传递给SQL查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆