-1

我正在尝试从 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")
4

2 回答 2

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
.....
于 2012-08-29T05:49:35.903 回答
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
于 2012-08-29T06:06:14.267 回答