I have create a library management system. here if I want to update a book's particular record its updating all the records in the SQL-server database. how can I write code for update a particular record only. here is my code,
Private Sub btnedit_Click(sender As Object, e As EventArgs) Handles btnedit.Click
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Add a WHERE clause in your SQL command to specify which book will be updated..
use the ID number of the book you want to update.
and avoid concatenating in your sql command, use parameter #
Dim comd As New SqlCommand("update Book set Book_Id=#bookID, Bk_Name=#bkName, Author_Name=#author, Year_of_release=#release, Availability_of_bks=#avail WHERE Book_Id=#whereID", con)
comd.Parameters.Add("#bookID", SqlDbType.String).Value = TextBox1.Text
comd.Parameters.Add("#bkName", SqlDbType.String).Value = TextBox2.Text
comd.Parameters.Add("#author", SqlDbType.String).Value = TextBox3.Text
comd.Parameters.Add("#release", SqlDbType.String).Value = TextBox4.Text
comd.Parameters.Add("#avail", SqlDbType.String).Value = TextBox5.Text
comd.Parameters.Add("#whereID", SqlDbType.String).Value = "Book ID HERE"
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
You need to add a WHERE clause to your SqlCommand so that SQL Server knows what record to update. Without a WHERE clause, it will update the entire table. See below:
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "' WHERE Book_Id='{**Put your book id here**}'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Related
This is my problem:
When I click update button, I don't know how to fix this error:
My Error Message is:
"Error: syntax error in union query"
This is my code:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Try
Dim cmd As OleDbCommand
Dim sql As String
sql = "(UPDATE tblUsers SET Username = '" & txtUserName.Text & "', Password = '" & txtUserPassword.Text &
"', Usertype = '" & cbousertype.Text & "', WHERE UserID = '" & txtUserID.Text & "');"
cmd = New OleDbCommand(sql, Conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
Is it wrong?
Now my problem has been solved thank you very much
i changed my code to use a parameters and then it work
Now my code is :
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE tblUsers SET Username=?, [Password]=?, Usertype=? where UserID=?"
cmd = New OleDbCommand(sql, Conn)
cmd.Parameters.AddWithValue("#p1", txtUserName.Text)
cmd.Parameters.AddWithValue("#p2", txtUserPassword.Text)
cmd.Parameters.AddWithValue("#p3", cbousertype.Text)
cmd.Parameters.AddWithValue("#p4", txtUserID.Text)
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Updated", MsgBoxStyle.Information, "Updated")
ShowUser()
End Sub
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.
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
I have written code in VB to delete a table record from database using inputbox (through user choice), but I have one problem when user inserts wrong value it still shows the "Record Successfully Deleted" MessageBox!
How to set the "if condition" to display record does not exist instead of showing successful deletion message?
Sorry this is my 1st post here that's why it is long! :p
Here is the code:
Private Sub btndelete_Click(sender As Object, e As EventArgs) Handles btndelete.Click
Try
Dim isbn As Long = InputBox("Enter Book ISBN", "Delete")
'First will delete the dependant record from published_by, book_return, memberbook_issue because
'it can not be deleted by applying on cascade delete or update cause it has composite primary key.
cmd = New SqlCommand("delete from published_by where isbn =" & isbn, cn)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cmd = New SqlCommand("delete from book_return where isbn =" & isbn, cn)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cmd = New SqlCommand("delete from memberbook_issue where isbn =" & isbn, cn)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cmd = New SqlCommand("delete from book where isbn = " & isbn, cn)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
cmd.ExecuteNonQuery()
da = New SqlDataAdapter("select b.staff_id, b.pub_id, b.sub_code, b.isbn, b.book_name, b.author, b.price, b.rack_no, b.no_of_books, pby.vol_no, pby.pub_date from book b join published_by pby on b.isbn = pby.isbn", cn)
dt = New DataTable
da.Fill(dt)
dgvbook.DataSource = dt
MessageBox.Show("Record Successfully Deleted from current table & dependant table(s)", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show("Not Completed Because OF The Following Error " & "%" & ex.Message & "%", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
As others have already mentioned, you really need to look into parameterizing your query. You should also look to encapsulate this into a stored procedure for easier reading and maintainablity. Those things aside, you can accomplish all of this in one database call.
This snippet should produce the expected results. Please double check the data type on the SqlParameter -- I guessed what it could be.
cmd = New SqlCommand("IF EXISTS(SELECT * FROM book WHERE isbn = #isbn) " _
& " BEGIN " _
& " delete from published_by where isbn = #isbn; " _
& " delete from book_return where isbn = #isbn; " _
& " delete from memberbook_issue where isbn = #isbn; " _
& " delete from book where isbn = #isbn;" _
& " SELECT 1; " _
& " END " _
& " ELSE SELECT 0", cn)
cmd.Parameters.Add(New SqlParameter("#isbn", SqlDBType.VarChar, 20) With {.Value = isbn})
cn.Open()
Dim returnValue as Integer = CInt(cmd.ExecuteScalar())
If returnValue = 1 Then
MessageBox.Show("Record Successfully Deleted from current table & dependant table(s)", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End
i have a few error. i have a search function from the database. when i run the project, and click the SEARCH button to view in the listview, the popup message out called "Incorrect syntax near "CONCAT". here the code for CONCAT
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
here full code for SEARCH function
Private Sub Search()
ListViewRoom.Items.Clear()
Dim item As New ListViewItem
Dim _isFound As Boolean = False
Dim colName() As String = {"Room_Code", "Room_Type", "Room_No", "Room_Price", "Room_Status", "No_of_Occupancy"}
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Using con As New SqlClient.SqlConnection("Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True")
Using com As New SqlClient.SqlCommand()
With com
.Connection = con
.CommandType = CommandType.Text
.CommandText = strSqlSearch
.Parameters.AddWithValue("#valueName", txtSearch.Text)
End With
Try
con.Open()
Dim dr As SqlClient.SqlDataReader = com.ExecuteReader
While dr.Read
_isFound = True
item = ListViewRoom.Items.Add(dr("Room_Code").ToString)
item.SubItems.Add(dr("Room_Type".ToString))
item.SubItems.Add(dr("Room_No".ToString))
item.SubItems.Add(dr("Room_Price".ToString))
item.SubItems.Add(dr("Room_Status".ToString))
item.SubItems.Add(dr("No_of_Occupancy".ToString))
End While
If Not _isFound Then
MsgBox("No results found.", MsgBoxStyle.OkOnly, "Information")
End If
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Using
End Using
End Sub
I hope u can help me. Tq
You don't need to use the CONCAT. just remove it from the SQL and it should work.
EDIT
Try this:
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%'+ #valueName +'%'"
Edit #2
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%" & txtSearch.Text & "%'"
And remove the parameter form the SqlCommand.