使用文本框从具有特定范围的 SQL Server 数据库中选择 [英] Select from SQL Server database with specific range using textbox
问题描述
Try
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "select * from MYTABLE where Year >='#" & Txtfromyear_reprt.Text & "#' and Year <='#" & Txttoyear_reprt.Text & "#'"
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "MYTABLE")
DgvReport.DataSource = ds.Tables("MYTABLE")
da.Dispose()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
我正在处理我的学校项目,但遇到了无法解决的问题.我在搜索按钮中编写了这段代码,但是当我在运行时单击它时,我的数据网格中没有显示任何数据.
I'm working with my school project but I've encountered a problem in which I can't solve. I wrote this code in my search button but when I click it at runtime, no data is displayed in my datagrid.
我想要的是当我单击它时,我想使用两个文本框将 mytable 中的所有数据显示到 Datagrid 视图中.我有两个文本框,txtfromyear
和 txttoyear
以及一个数据类型为 nvarchar(50)
的数据库列 Year
.
What I want is when I click it I want to display all the data from mytable to the Datagrid view using two textboxes. I have two textboxes, txtfromyear
and txttoyear
and a database column Year
with a datatype nvarchar(50)
.
请帮助我,在此先感谢您.
Please help me, thank you in advance.
推荐答案
不要使用字符串连接来构建 sql 查询,永远不要!
Don't use string concatenation to build your sql queries, NEVER!
你对sql注入持开放态度,没有任何借口.而是使用 sql 参数:
You are open for sql injection, there is no excuse for it. Instead use sql parameters:
Dim dateFrom as Date
Dim dateTo as Date
Dim validFromDate = Date.TryParse(Txtfromyear_reprt.Text.Trim(), dateFrom)
Dim validToDate = Date.TryParse(Txttoyear_reprt.Text.Trim(), dateTo)
如果用户没有提供有效日期,现在用有意义的消息退出此方法.您可以检查 validFromDate
和 validToDate
它们是布尔值.其余代码执行If validFromDate AndAlso validToDate
:
Now exit this method with a meaningful message if the user didn't provide valid dates. You can check validFromDate
and validToDate
which are booleans. The rest of the code is executed If validFromDate AndAlso validToDate
:
Dim str As String = "select * from MYTABLE where Year >= @fromyear and Year <= @toyear"
da = New SqlDataAdapter(str, conn)
da.SelectCommand.Parameters.Add("@fromyear", SqlDbType.DateTime).Value = dateFrom
da.SelectCommand.Parameters.Add("@toyear", SqlDbType.DateTime).Value = dateTo
' now you can use da.Fill(ds, "MYTABLE") safely
<小时>
我刚刚看到您使用 varchar
来存储 datetimes
.为什么?在数据库中修复它.
I just saw you use varchar
to store datetimes
. Why? Fix it in the database.
这篇关于使用文本框从具有特定范围的 SQL Server 数据库中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!