我正在尝试从sql-vb.net
中检索最大值这是我的代码:我收到此错误:
无法将“System.DBNull”类型的对象强制转换为类型 'Oracle.DataAccess.Client.OracleDataReader'的
请帮忙。 :(
Dim cmd2 As New OracleCommand
cmd2.Connection = conn
'SELECT MAX(LASTNO) FROM d001005 where lbrcode = '104' and CODE1 = 'CASH' and lnodate = '14-NOV-08'
Dim datepara As String = Date.Now.ToString("dd-MMM-yy")
'datepara = "14-NOV-08"
cmd2.CommandText = "SELECT MAX(LASTNO) FROM d001005 where lbrcode = '" + lbr + "' and CODE1 = 'CASH' and lnodate = '" + datepara + "'"
cmd2.CommandType = CommandType.Text
Dim dr2 As OracleDataReader = cmd2.ExecuteScalar
Dim result As Decimal = dr2.Item("LASTNO")
答案 0 :(得分:3)
方法ExecuteScalar()
返回System.Object
,因此请更改您的代码。
Dim value=cmd2.ExecuteScalar()
IF Not IsNoThing(value) Then
result=Decimal.Parse(value.ToString())
End IF
或者你可以使用ExecuteReader,
Dim dr2 As OracleDataReader = cmd2.ExecuteReader()
Dim value as Decimal
If dr2.Read() Then
IF Not dr2.IsDbNull(0)
Value=dr2.GetDecimal(0)
End IF
End If
并且总是使用参数而不是硬编码的sql字符串。
cmd2.CommandText = "SELECT MAX(LASTNO) FROM d001005 where lbrcode=@lbrcode and CODE1='CASH' and lnodate=@lnodate"
cmd2.Parameters.Add("@lbrcode",SqlDbType.VarChar,20).Value=lbr
.....
答案 1 :(得分:2)
当您使用聚合函数来查找最大值时,没有名称为“LASTNO”的项目。此外ExecuteScalar会返回第一行的第一个值!另一点是,您应该将 OracleParameter 用于任何类型的动态语句,以防止SQL注入!
Dim cmd2 As New OracleCommand
cmd2.Connection = conn
Dim datepara As String = Date.Now.ToString("dd-MMM-yy") ' see hint below
cmd2.CommandText = "SELECT MAX(LASTNO) as maxLastNo FROM d001005 where lbrcode = :lbr and CODE1 = 'CASH' and lnodate = :lnodate"
' add parameter value directly
cmd2.Parameters.AddWithValue("lbr", lbr) ' lbr seems to be your var which holds the according value
' or create parameter object and set type and add it afterwards
Dim param as new OracleParameter
param.ParameterName = "lnodate"
param.Value = datepara ' or any other value (furthermore: no need to convert to string)
param.ParameterType = OracleType.DateTime ' or OracleType.Varchar which is set by default
cmd2.CommandType = CommandType.Text
Dim val = cmd2.ExecuteScalar()
if Not val is Nothing then
Dim maxValue as Decimal = Convert.ToDecimal(val)
Console.WriteLine(maxValue)
End if