My code is now this, as i forgot to add the connection to my database after i updated the table, still doesnt work though
Private Sub cmdRegistar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegistar.Click
myConnToAccess = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = 'D:\PAP\LoginForm\LoginForm\bin\debug\login.mdb'")
myConnToAccess.Open()
Try
Dim x As String
Dim str As String
x = ComboBox1.Text
str = "UPDATE UserTable set Password = '" & txtPass.Text & "' where Username = '" & x & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnToAccess)
myConnToAccess.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So as you can see the code doesnt have any errors, it compiles and runs just fine, it just doesnt work, the combobox values come from the same database of what i'm trying to do with the command update. All my others conections work just fine, my add, search.
When are you actually passing str to your database? Shouldn't you have something like str.Execute or something in there? Aside from that, you also have an error in this line:
str = "UPDATE UserTable set Password" & txtPass.text & "where Username= '" & x & "'"
It should be:
str = "UPDATE UserTable set Password = '" & txtPass.text & "' where Username = '" & x & "'"
Password is a reserved word, so try this:
str = "UPDATE UserTable set [Password] = '" & txtPass.Text & "' where Username = '" & x & "'"
Related
Please I need your help. I am trying to save a file in a SQL Server database, but it is showing this error
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
Here is my code
Private Sub Button70_Click(sender As Object, e As EventArgs) Handles Button70.Click
fna = content.Text
fna.Split("\")
ffn = fna.Last.ToString
conn.Open()
Dim com As New SqlCommand
com.Connection = conn
com.CommandText = "insert into meeting (Date_Entry, Title, Chairperson, Venue, File_Name, [Content]) values( '" & date5.Text & "', '" & title.Text & "', '" & cp.Text & "', '" & vn.Text & "', '" & f_name.Text & "', '#[Content]')"
With com.Parameters
.AddWithValue("Content", SqlDbType.VarBinary).Value = File.ReadAllBytes(content.Text)
End With
com.ExecuteNonQuery()
conn.Close()
MsgBox("File saved")
content.Clear()
End Sub
Private Sub Button25_Click(sender As Object, e As EventArgs) Handles Button25.Click
'// open dilogue to add file to save
If op.ShowDialog = Windows.Forms.DialogResult.OK Then
content.Text = op.FileName
End If
End Sub
You should use #Content instead of #[Content] in your query string.
Im having a problem of adding records when I click the messagebox and i answered is no then cancel it and add another record but im having a message of connection has not been initialized heres my code thank you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim reader As SqlDataReader
conn.Open()
Dim bday As String
bday = adyear.Text & "-" & admonth.Text & "-" & adday.Text
If adfirstname.Text.Length < 2 Then
MessageBox.Show("Firstname is too short")
End If
Dim exist As String
exist = "select * from record where firstname='" & adfirstname.Text & "'" & " and lastname='" & adlastname.Text & "';"
cmd = New SqlCommand(exist, conn)
reader = cmd.ExecuteReader
If reader.HasRows = True Then
If MsgBox("THE MEMBER YOU ARE TRYING TO ADD HAS AN SAME FIRSTNAME AND LASTNAME IN THE RECORD DO YOU WISH TO CONTINUE ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
ElseIf adage.Text < 18 Then
If MsgBox("The member is less than 18 years old is this an intern?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim add As String
add = "insert into record(firstname,middlename,lastname,birthday,age,jobposition)" & _
"values(" & _
"'" & adfirstname.Text & "'," & _
"'" & admiddlename.Text & "'," & _
"'" & adlastname.Text & "'," & _
"'" & bday & "'," & _
"'" & adage.Text & "'," & _
"'" & adjobposition.Text & "');"
cmd = New SqlCommand(add, conn)
cmd.ExecuteNonQuery()
MessageBox.Show("Added Complete")
Else
MsgBox("Action is Terminated")
' code for return to adding and stop the messagebox of the connection has not been initialized
End If
End If
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
Well, since it appears the conn is a form level object you would need to call
conn = New SqlConnection(<connection string>)
before you can use it to open the connection. Given that you call
conn.Dispose()
to destroy the conn instance in the Finally block it appears that you do not keep an open connection around for long.
I have 4 tables: Code_Product, Name_Product, Color_Product, Size_Product
And code:
Public Sub ExecuteQuery(query As String)
Dim command As New SqlCommand(query, connection)
command.ExecuteNonQuery()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
ExecuteQuery(updateQuery)
MessageBox.Show("Data has been changed")
Notes: the code work.
But, the code changes all columns, and I just want to change only one column. How?
replace this line
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
with this. Pass only that column which you want to update.
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
I am trying to make a banking system where the customer will only be able to deposit money IF ONLY they enter the CORRECT AccountNo & Name using Microsoft Access Databse in VB NET.
Here are my codes:
Dim conn As New OleDbConnection
Dim conn = "provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Database\Bank-Application-Database.accdb;"
conn.ConnectionString = "provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Database\Bank-Application-Database.accdb;"
cmdupdate.Connection = cnnOLEDB
Dim deposit As OleDbCommand = New OleDbCommand("SELECT * FROM [Current_Account] WHERE [AccountNo] and [CustomerName] = '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "' AND [Amount] = '" & amounttxt.Text & "'", myConnection)
deposit.Connection = conn
conn.Open()
If accnotxt.ToString = True And nametxt.ToString = True Then
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = '" & amounttxt.Text.ToString & " WHERE [AccountNo] AND [CustomerName] = " & accnotxt.Text.ToString & " " & nametxt.ToString & ";"
cmdupdate.CommandType = CommandType.Text
cmdupdate.ExecuteNonQuery()
MsgBox(" Successfully deposited.")
Else
MsgBox("Incorrect Account Number or Name.")
I am able to run.However when I click to Deposit, this is the error.
The error I got:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "System.Windows.Forms.TextBox, Te" to type 'Boolean' is not valid.
Any helpers ? Thanks in advance.
In addition to #Jonathon Ogden's answer:
You missed your single quotes in this query:
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = '" & amounttxt.Text.ToString & " WHERE [AccountNo] AND [CustomerName] = " & accnotxt.Text.ToString & " " & nametxt.ToString & ";"
Change it to this:
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = " & Val(amounttxt.Text) & " WHERE [AccountNo]= '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "';"
I also removed there the single quote from amounttxt.Text.ToString assuming it's a value, changed it to Val(amounttxt.Text) so that even that textbox is blank, it won't cause an error.
Also corrected your WHERE Condition:
Another is you don't need .ToString anymore since .Text property is already a String.
Your ToString usage will convert the value of the accnotxt and nametxt text boxes into a text string and you're trying to compare that to True (i.e. accnotxt.ToString = True) which is of a Boolean data type not a String data type i.e. you are trying to compare text to a boolean (true or false) value.
A very basic way (that can be improved on) of doing the account number and name check would be to change your SELECT statement to:
Dim deposit As OleDbCommand = New OleDbCommand("SELECT * FROM [Current_Account] WHERE [AccountNo] and [CustomerName] = '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "'", myConnection)
I removed the Amount filter from the WHERE clause as I am not sure why you are doing that. You don't even use this deposit database command. You then execute the deposit SQL command and get its result: Dim result = deposit.ExecuteScalar(). ExecuteScalar does the following:
Executes the query, and returns the first column of the first row in the result set returned by the query.
You then change your account number and name check to If result IsNot Nothing Then instead of checking if the values of the textboxes are a particular account number and name.
In other words, if your query returns something and not nothing, then you can assume a current account exists with the accnotxt and nametxt.
Also, pay attention to #CrushSundae answer as they have highlighted other issues too.
In the below code, my second query will not insert into the SQL database, but the first one will update. I can copy the query (from the msgbox i added for testing) and paste it in SQL Server Management Studio, and it will execute fine. I also do not get any error messages back from SQL, though i'm not sure if that code is correct (it was copied + pasted from another source). Also, can i simplify the code to pass both queries at the same time?
Dim Conn As New System.Data.SqlClient.SqlConnection 'sql server datastream connection
Dim Cmd As New System.Data.SqlClient.SqlCommand 'sql command vars
Dim SqlQuery As String 'string var used to hold various SQL queries
Dim data As System.Data.SqlClient.SqlDataReader 'datareader object variable
Dim MVDataset As New DataSet
Dim MVDatatable As DataTable
Dim MVDatarow As DataRow
Private Sub MVUpdateButton_Click(sender As Object, e As EventArgs) Handles MVUpdateButton.Click
vbyn = MsgBox("Are you sure you want to update Tally Sheet Master Variables?" & vbCrLf & vbCrLf & "Changes to these variables will change the functionality of the Tally Sheet!", vbYesNo, )
Try
Select Case vbyn
Case vbNo
GoTo MVTableUpdateBypass
Case vbYes
'get new data from textboxes
Vers = TextBox1.Text
If TextBox2.Text = True Then
Testing = 1
Else
Testing = 0
End If
FlatFeeCharge = TextBox3.Text
PrepricingCharge = TextBox4.Text
SendMailAcct = TextBox5.Text
SendMailPW = TextBox6.Text
TestingEmail = TextBox7.Text
PrePricingEmail = TextBox8.Text
ImperataEmail = TextBox9.Text
'update existing active row to mark inactive
SqlQuery = "Update MasterVars set Active = 0 where PKEY = " & PKEY & ";"
MsgBox(SqlQuery)
If Conn.State = ConnectionState.Closed Then
Conn.ConnectionString = "Data Source=SQL01;Initial Catalog=TallySheet;Integrated Security=SSPI;"
End If
Conn.Open()
Dim MVDataAdapter As New SqlDataAdapter(SqlQuery, Conn)
Dim MVUpdateCommand As SqlCommand
MVUpdateCommand = New SqlCommand(SqlQuery)
MVDataAdapter.UpdateCommand = MVUpdateCommand
'insert new active row
SqlQuery = "Insert into MasterVars (Vers, Testing, FlatFeeCharge, PrePricingCharge, SendMailAcct, SendMailPW, TestingEmail, PrePricingEmail, ImperataEmail, DTS, UserName, Active) Values (" & "'" & Vers & "', " & Testing & ", '" & FlatFeeCharge & "'" & ", '" & PrepricingCharge & "'" & ", '" & SendMailAcct & "'" & ", '" & SendMailPW & "'" & ", '" & TestingEmail & "'" & ", '" & PrePricingEmail & "'" & ", '" & ImperataEmail & "'" & ", '" & Date.Now & "'," & "'QGDOMAIN\" & Environment.UserName & "'," & 1 & ");"
MsgBox(SqlQuery)
Dim MVInsertCommand As SqlCommand
MVInsertCommand = New SqlCommand(SqlQuery)
MVDataAdapter.InsertCommand = MVInsertCommand
MVDataAdapter.Fill(MVDataset, "MasterVars")
End Select
Catch ex As SqlException
Dim i As Integer
Dim errormessages As String
errormessages = ""
For i = 0 To ex.Errors.Count - 1
errormessages = errormessages & " " & ("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
Console.WriteLine(errorMessages.ToString())
End Try
'reload form with updated variables
Conn.Close()
Conn.Dispose()
MVTableUpdateBypass:
End Sub
The Fill method of the SqlDataAdapter executes the SelectCommand not the UpdateCommand or the InsertCommand. In any case these two commands (and the DeleteCommand) are executed when you call the Update method of the adapter.
Moreover the Update method runs the commands looking for rows changed/added/deleted in the DataTable/DataSet retrieved by the SelectCommand and works only for those rows.
But you don't need an SqlDataAdapter to execute your two queries. You should simply construct an SqlCommand with both texts separated by a semicolon and call ExecuteNonQuery
SqlQuery = "Update MasterVars set Active = 0 where PKEY = #key;" & _
"Insert into MasterVars (Vers, Testing, .....) VALUES (#p1, #o2, ....)"
Using Conn = New SqlConnection("Data Source=SQL01;......")
Using cmd = New SqlCommand(SqlQuery, Conn)
Conn.Open()
cmd.Parameters.Add("#key", SqlDbType.Int).Value = PKEY
cmd.Parameters.Add("#p1", SqlDbType.NVarChar).Value = vers
cmd.Parameters.Add("#p2", SqlDbType.Int).Value = testing
... and so on with other parameters ....
cmd.ExecuteNonQuery()
End Using
End Using
In this incomplete example (too many parameters to write down) I have concatenated the two sql texts in a single string and prepared it with parameter placeholders. Then I build the parameter collection with the exact datatypes required by your table and finally call ExecuteNonQuery to run everything on the database side.
Notice that is not needed to keep global objects like the connection or the command. It is always better to create a local variable, use and destroy it when done. In particular disposable objects like the connection and the command should always created in a Using block