Why this error .. command text was not set to command object - vb.net

conn.Open()
Try
Dim update As New OleDbCommand
update.Connection = conn
update.CommandText = " UPDATE O_name SET fname= '" & Name1.Text & "' WHERE ID = '" & ID.Text & "'"
update.ExecuteNonQuery()
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
conn.Close()
there is always Error
" Command Text was not set to command object "
what's the reason
please don't talk about parametrized query cause i'm asking about this specifically

A quick google for the error message has a link to this page as the first search result, where someone writes:
The problem was EvaluateAsExpression was not set to true..its working now..thanks again for the help :)
What kept you from using Google and finding it as quicky as I did?

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

Sql query to update new values to column Visual Basic

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.
Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.

update statement not working although code is right

my update statement not working .. there is no effect on database when i check it
here is the code
conn.Open()
Try
Dim update As New OleDbCommand
update.Connection = conn
update.CommandText = " update O_name set fname = ' " & Name1.Text & " ' where ID = ' " & ID.Text & " ' "
update.ExecuteNonQuery()
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
conn.Close()
Using connection As New OleDbConnection(connectionString)
Using command As New OleDbCommand("update O_name set fname =? where ID =?", connection)
command.Parameters.AddWithValue("p1", Name1.Text)
command.Parameters.AddWithValue("p2", ID.Text)
command.Connection.Open()
command.ExecuteNonQuery()
MsgBox("done")
End Using
End Using
use parameters but you need to specify parameters by using ?, because :
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
UPDATE:
You have additional spaces in your parameter value assign, try below
update.CommandText = String.Format("UPDATE O_name SET fname ='{0}' WHERE ID ='{1}'",Name1.Text, ID.Text)

VB Custom login page. Incorrect syntax near '.'.

I am creating a custom log in page using VB in Visual Studio. Every time I try logging in, however, I get the following error:
"Incorrect syntax near '.'".
When I put in the wrong username/password combo it recognizes this, but when it is right it will get this error and fail to log in.
Private Function VerifyLogin(ByVal UserName As String) As Boolean
Try
Dim cnn As New Data.SqlClient.SqlConnection
cnn.ConnectionString = My.MySettings.Default.RedwoodConnectionString.Replace(";Integrated Security=True", ";Integrated Security=False") & UserSetting
Dim cmd As New Data.SqlClient.SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT COUNT (principal_id) FROM _ sys.database_principals WHERE(name = '" & UserName & "')"
cnn.Open()
Dim i As Integer
i = cmd.ExecuteScalar()
cnn.Close()
If (i > 0) Then Return True
Return False
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Error: " & ex.Message & vbNewLine & "Location: VerifyLogin() in Login.vb" & vbNewLine & "Returned value: False")
Return False
End Try
End Function
Look at this portion of your sql:
FROM _ sys.database_principals
See the mistake there? It thinks the _ is the full table name and sys is an alias. At this point, .database_principals is no longer valid, hence your error.
And while we're at it, you really need to fix the sql injection vulnerability!!

Looking for the best way to use ExecuteScalar()

This code works. It's based on some code I found on the internet.
Can you tell me if the coding is the best way to get a scalar value and if there is a better way can you show coding samples?
Dim objParentNameFound As Object
TextBoxParentsName.Text = ""
If TextBoxParentID.Text <> "" Then
' Display the parent's name using the parent ID. '
Dim strSqlStatement As String = "Select FatherName " & _
"From Parents " & _
"Where ID = #SearchValue"
' Set up the sql command and lookup the parent. '
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Add SqlParameters to the SqlCommand. '
.Parameters.Clear()
.Parameters.AddWithValue("#SearchValue", TextBoxParentID.Text)
' Open the SqlConnection before executing the query. '
Try
ObjConnection.Open()
Try
objParentNameFound = .ExecuteScalar()
If objParentNameFound <> Nothing Then
' Display the parent name here. '
TextBoxParentsName.Text = objParentNameFound
End If
Catch exSqlErrors As SqlException
MessageBox.Show("Sorry, I couldn't execute your query because of this error: " & _
vbCrLf & vbCrLf & exSqlErrors.Message, _
"Error")
End Try
Catch exErrors As Exception
MessageBox.Show("Sorry, there was an error. Details follow: " & _
vbCrLf & vbCrLf & exErrors.Message, _
"Error")
Finally
ObjConnection.Close()
End Try
End With
End Using
End If
The Microsoft Access Application block has some nice examples of how to use ADO.Net. In particular what you might find helpful is how they've organized tasks such as ExecuteScalar() into a series of overloaded methods making it easy to invoke the process you need.
The sample you posted would greatly benefit from separating out the concerns. In other words, take the code you use to build up the connection, command and parameters and make that a separate method or methods. This allows the code to be reused without copy& pasting it throughout your codebase. This allows your calling code to simply pass in the parameter(s) and bind the result to your text box or other controls.
Edit: Example
Assuming you use the SqlHelper.vb class you can do something like the following:
Dim searchValue As Integer = 1
Dim myConnectionString As String = "MyConnectionString"
Dim sqlStatement As String = "SELECT FatherName FROM Parents WHERE ID = #SearchValue"
Dim paramList(0) As SqlParameter
paramList(0) = New SqlParameter() With {.Value = searchValue, .ParameterName = "#SearchValue"}
TextBoxParentsName.Text = SqlHelper.ExecuteScalar(myConnectionString, CommandType.Text, sqlStatement, paramList).ToString()