[英]how to handle exceptions in vb.net?
I am creating a program in which a user can search and add their desired order. 我正在创建一个程序,用户可以在其中搜索并添加所需的订单。 The problem that I'm facing now is that when I throw the exception, the program does not read the exception so that the user will know if the id that is entered is on the database or not. 我现在面临的问题是,当我引发异常时,程序不会读取异常,因此用户将知道输入的ID是否在数据库中。 I will provide the code snippet of the program that I'm working on. 我将提供我正在处理的程序的代码片段。
Problems 问题
item_code
does not exist in your database. 如果item_code
在数据库中不存在,则您的代码不会引发错误。 It will simply not enter the while
loop. 它根本不会进入while
循环。 item_code
exists is a check if the datareader has results. 检查item_code
存在的正确方法是检查数据item_code
是否有结果。 ';DROP TABLE Products;-
例如,如果用户恶意输入以下文本,它将删除整个Products表: ';DROP TABLE Products;-
OleDbConnection
or the OleDbCommand
objects correctly. 您没有正确处理OleDbConnection
或OleDbCommand
对象。 If an exception occurs, your code will not run the Dispose()
method. 如果发生异常,您的代码将不会运行Dispose()
方法。 This can cause you to quickly run out of resources. 这可能会导致您快速耗尽资源。 Solutions 解决方案
You should check if the dataRead
has any rows. 您应该检查dataRead
是否有任何行。 If it does not, then you can alert the user via javascript. 如果不是, 则可以通过javascript提醒用户。 Like so: 像这样:
If dataRead.HasRows Then //READ DATA Else //ALERT USER End If
Solution #1 address Problem #2 as well 解决方案1也解决了问题2
Use a parameterized query. 使用参数化查询。 The .NET framework will prevent these kinds of attacks (SQL Injection). .NET框架将防止此类攻击(SQL注入)。
selectProductQuery = "SELECT * FROM Products WHERE item_code = @item_code" ... newCmd.Parameters.AddWithValue("item_code", txtItemCode.Text);
Wrap all objects that implement Dispose()
in a using block. 将所有实现Dispose()
对象包装在using块中。 This will guarantee everything is properly disposed of, whether an error is thrown or not. 这将确保正确处理所有内容,无论是否引发错误。
Using newCon As New OleDbConnection(....) Using newCmd As New OleDb.OleDbCommand(...) ... End Using End Using
To be perfectly honest, there is quite a bit "wrong" with your code, but this should get you headed in the right direction. 老实说,您的代码有很多“错误”,但这应该使您朝正确的方向前进。
The line: 该行:
Response.Write(<script>alert('The ...')</script>)
Needs to be (note the quotes): 需要是(请注意引号):
Response.Write("<script type='text/javascript'>alert('The ...')</script>")
Same for the other one at the top, but I dont think that will fix your overall problem. 顶部的其他人也一样,但我认为这不会解决您的整体问题。
Instead, use javascript like this: 相反,请使用如下所示的javascript:
if(!alert('Whoops!')){window.location.reload();}
to pop up an alert box and then reload the page after they click on the button. 弹出警报框,然后在他们单击按钮后重新加载页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.