-
Jul 22nd, 2020, 01:56 PM
#1
Thread Starter
Hyperactive Member
ExecuteScalar: CommandText property has not been initialized
One ASP.NET project keeps on receiving a message below from "Try...Catch...End try" block.
System.InvalidOperationException: ExecuteScalar: CommandText property has not been initialized
I searched Google but can't get help.
Is this SQL script mistake? Please help.
---------------------------------------------------------
It points at a function from app below
dim iCount as Int32 = 0
dim SQL as string = "Select count(*) from ORDER where[OrderCity]='London'"
iCount = GetCountScalar(SQL) //Error message point at the function in this line
Public Function GetCountScalar(ByVal strSQL As String) As Integer
Dim ret As Int32 = 0
Using myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString")) '
myConnection.Open()
Using mySQLCommand = New SqlCommand(strSQL, myConnection)
mySQLCommand.CommandType = CommandType.Text
ret = CInt(mySQLCommand.ExecuteScalar)
End Using
End Using
Return ret
End Function
-
Jul 22nd, 2020, 02:08 PM
#2
Re: ExecuteScalar: CommandText property has not been initialized
When you post code please put it inside code tags so it is displayed in a more readable way - either using the # or VB buttons in the post editor screen (or at the top of the Quick Reply box), or by putting them in manually, like this: [code] code here [/code]
The word Order is not valid a name for a table/field/etc, because it is a keyword (as in "Order By").
Change the name if you can, otherwise use square brackets as you did with [OrderCity]
-
Jul 26th, 2020, 12:02 PM
#3
New Member
Re: ExecuteScalar: CommandText property has not been initialized
You may consider changing the table name from ORDER to tblorder cos ORDER is a reserve word as said by si_the_geek
-
Jul 27th, 2020, 12:26 AM
#4
Re: ExecuteScalar: CommandText property has not been initialized
I doubt the connection is not opened correctly. Refer to this link for correct way of using Sqlcommmand.
Code:
Shared Public Function AddProductCategory(ByVal newName As String, ByVal connString As String) As Integer
Dim newProdID As Int32 = 0
Dim sql As String = "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); " & "SELECT CAST(scope_identity() AS int)"
Using conn As SqlConnection = New SqlConnection(connString)
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
#cmd.Parameters.Add("@Name", SqlDbType.VarChar)
#cmd.Parameters("@name").Value = newName
Try
conn.Open()
newProdID = CType(cmd.ExecuteScalar(), Int32)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return CInt(newProdID)
End Function
Please mark you thread resolved using the Thread Tools as shown
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|