gpt4 book ai didi

.net - SqlDataReader.ExecuteReader 没有异常,而 SQL Server 返回转换错误

转载 作者:行者123 更新时间:2023-12-04 04:36:41 25 4
gpt4 key购买 nike

当我在 SQL Server Management Studio 中执行以下语句时

exec sp_executesql N'select 1 其中 1 = @p1',N'@p1 nvarchar(3)',@p1=N'a'



我收到以下错误

消息 245,第 16 级,状态 1,第 1 行

将 nvarchar 值“a”转换为数据类型 int 时转换失败。

但是当我使用 ExecuteReader 时,我没有得到任何异常

为什么?

如何在应用程序中将此错误作为异常获取和处理

导入 System.Data.SqlClient

模块模块1

Sub Main()

Dim TestSqlConnection As SqlConnection = Nothing

Dim TestSqlCommand As SqlCommand = Nothing

Dim TestReader As SqlDataReader = Nothing

Dim TestGetSchemaTable As DataTable = Nothing

TestSqlConnection = New SqlConnection
TestSqlConnection.ConnectionString = "Data Source=(local);Database=master;Integrated Security=true"
TestSqlConnection.Open()
TestSqlCommand = New SqlCommand()
TestSqlCommand.Connection = TestSqlConnection
TestSqlCommand.CommandType = CommandType.Text
TestSqlCommand.CommandText = "select 1 where 1 = @p1"

Dim TestSqlParameter As SqlParameter = New SqlParameter
TestSqlParameter.ParameterName = "@p1"
TestSqlParameter.SqlDbType = SqlDbType.NVarChar
TestSqlParameter.Size = 3
TestSqlParameter.Direction = ParameterDirection.Input
TestSqlParameter.Value = "a"
TestSqlCommand.Parameters.Add(TestSqlParameter)

Try
TestReader = TestSqlCommand.ExecuteReader()
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try
End Sub

端模块

最佳答案

ExecuteReader 实际上并不执行查询。第一次调用 .Read() 会抛出错误。

如果你只想捕获 SqlException您可以执行以下操作:

Try
TestReader = TestSqlCommand.ExecuteReader()
TestReader.Read()
Catch ex As SqlException
Console.WriteLine("SQL error.")
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try

关于.net - SqlDataReader.ExecuteReader 没有异常,而 SQL Server 返回转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19634521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com