In my game I need to save the score after the user has logged in. The user who has logged in has their name displayed in a textbox on the form. I am having trouble overwriting the score field specific to the user.
My current code that saves the score and level to a new row and not the user who is logged in:
cmd.CommandText = "INSERT INTO tbl_User ([Score], [Level])VALUES(#Score, #Level) WHERE User='" & txtUser.Text & "'"
cmd.Parameters.AddWithValue("#Score", lblScore.Text) 'Adds score to table
cmd.Parameters.AddWithValue("#Level", lblLevel.Text) 'Adds level to table
Thanks
If you need to overwrite you need to use UPDATE command and not INSERT, like:
cmd.CommandText = "UPDATE tbl_User SET [Score]=#Score, [Level] = #Level WHERE User=#User"
cmd.Parameters.AddWithValue("#Score", lblScore.Text) 'Adds score to table
cmd.Parameters.AddWithValue("#Level", lblLevel.Text) 'Adds level to table
cmd.Parameters.AddWithValue("#User", txtUser.Text) 'Adds user to table
Related
I have a unique index of fields in my table in microsoft access. The fields are Shift, Operator, Date_Field, and Machine. I have a data entry form with combobox selections for these fields, except for the date which autopopulates today's date. I want to be able to navigate the form te the record that matches the existing Shift/Operator/Date/Machine combo if it already exists. I have a DLookup function that checks to see if such a record exists already, but now I need to know how to change the form so it is entering the data on that record instead of a new one.
Here's what I have so far. It is being activated in the AfterUdate of one of the last combobox in the tab order.
Dim int_ID As Integer
With Me
'checks if duplicate record exists and stores it as int_ID variable
int_ID = Nz(DLookup("ID", "Tracking", "Shift= " & Val(.ShiftCbo) & " And Operator='" & .OpCbo.Column(1) & "' And Date_Field=#" & .DateBox & "# And Machine='" & .MachineCbo.Column(1) & "'"), 0)
End With
If int_ID <> 0 Then
'I need to know what to put here to take the form to the existing record.
End If
I've tried to use Cmd.GoToRecord but that doesn't work.
One of my favorite (and simplest) methods is using Me.Recordsource
Once you have your code working correctly which defines the filter criteria, try something like this:
Me.Recordsource= "select * from UnderlyingFormMainQuery where TextColumnName='" & varString & "' or NumericColumnName=" & intSomething
Me.Requery
For i As Integer = 0 To dgclassinfo.Rows.Count - 1
LRN = dgclassinfo.Rows(i).Cells(2).Value.ToString
Lname = dgclassinfo.Rows(i).Cells(3).Value.ToString
Fname = dgclassinfo.Rows(i).Cells(4).Value.ToString
Mname = dgclassinfo.Rows(i).Cells(5).Value.ToString
comm.CommandText = "insert into g7(LRN,Lname,Fname,Mname ) values('" & LRN & "','" & Lname & "','" & Fname & "','" & Mname & "')"
comm.ExecuteNonQuery()
Next
I used to code above to import my data. Using dgv. My data is databound. for additional info. When I import the file it reads the value of the excel and displays in the dgv in which i insert the data using the for loop above. I think I need to use mydr.hasrows but I have no idea on how to do this using for loop. How can I check for duplicate records every row? LRN is my pk.
Any help will be appreciated.
To check if record exists, u can actually check the database's specific column to see if the column has any rows containing the same record u are trying to insert..TO do this,first u need to check the database for duplicates and then insert new data if no duplicates exist.A full example might look like this :
Dim cmd as new SqlCommand("Select * from TABLENAME([column names-remove brackets if required])values(#value1)",con)
cmd.parametres.AddWithValue("#value1",Firstname.Text)
Dim dr as new SqlDataReader=cmd.Executereader
If dr.hasRows Then 'This checks if any duplicates exist
Msgbox("Duplicates Found")
Else
Dim cmd as new SqlCommand("Inserting data query here",con)
cmd.parametres.Add("#value1",SqlDbtype.Varchar).value=Firstame.Text
cmd.ExecuteNonQuery
Here i've assumed u r using Sql Server, make necessary changes to the code
I am creating a login logout system for our College Library that records the students' time in and time out whenever they enter or exit in our library.
I am using VS 2010 Ultimate for the form and SQL server 2008 r2 for my database.
In my database
i have 3 tables
tblCollegeinfo Contains :
studentNumber(primary key),
studentName, and
studentCourse,
tblCollegeStudentLog contains their record with
studentNumber again as the foreign key,
studentTimeIn,
studentTimeOut,
studentDate and
LoginNo and
tblCollegeStudentPassword contains
their Passwords with studentNumber again
and studentPassword.
Actually my Log In button works, that whenever they entered their Username and Password and hit the Log In button they are now Logged In and their Student Number, Name, Course Login time (Time In) and Date appears in the ListView.
My problem is the Log out button. I don't know what correct code should i use. What correct SQL query should I use.
I have a hint that I should join the tables first and Insert the Log Out Time as the 'value' in the studentTimeOut of the table "tblCollegeStudentLog"
but I don't know how. Whenever I click the Log Out button with the SelectedItems in my ListView, instead the Logout Time(Time Out) inserted in the selected item it appears in another row. In short, how can I insert a value in a specified column together with the other columns without appearing into a new another row?
Please help me guys to solve this problem :( I hope you understand what I am trying to say :( I want that the inserted Value appears together with the other columns, because what only happens to me is that whenever i hit the Log Out button the value appears in another row alone it is not joining in the other columns :( thanks Guys!!!
Heres the code:
Private Sub btnLogoutNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogoutNow.Click
Connect()
cmd = New SqlCommand("SELECT tblCollegeStudentlog.LoginNo, tblCollegeStudentLog.studentNumber, tblCollegeInfo.studentName, tblCollegeInfo.studentCourse, tblCollegeStudentLog.studentTimeIn, tblCollegeStudentLog.studentTimeOut, tblCollegeStudentLog.studentDateIn FROM tblCollegeStudentLog LEFT OUTER JOIN tblCollegeInfo ON tblCollegeStudentLog.studentNumber = tblCollegeInfo.studentNumber WHERE tblCollegeStudentLog.studentNumber = '" + lvwLog.SelectedItems(0).Text + "'", con)
cmd.ExecuteNonQuery()
If dr.HasRows Then
cmd = New SqlCommand("INSERT INTO tblCollegeStudentLog (studentTimeOut) VALUES ('" + lblTimeOut.Text + "') WHERE studentNumber = '" + lvwLog.SelectedItems(0).Text + "' ", con)
cmd.ExecuteNonQuery()
MsgBox("You are now logged out!")
End If
End Sub
You need to use UPDATE, not INSERT. Assuming they are not able to log out unless they have logged in (i.e. there is record in tblCollegeStudentLog where StudentTimeIn is NULL, you can just use:
UPDATE tblCollegeStudentLog
SET StudentTimeOut = #OutTime
WHERE StudentNumber = #StudentNumber
AND StudentTimeOut IS NULL;
Then you would use SqlParameters to properly execute the command and not leave yourself vunerable to SqlInjection, poor SQL Plan caching and data type issues:
Dim Sql as String = "UPDATE tblCollegeStudentLog SET StudentTimeOut = #OutTime WHERE StudentNumber = #StudentNumber AND StudentTimeOut IS NULL;"
Using cmd = New SqlCommand(Sql, con)
cmd.Parameters.AddWithValue("#OutTime", Convert.ToDateTime(lblTimeOutNya.Text))
cmd.Parameters.AddWithValue("#StudentNumber", lvwLog.SelectedItems(0).Text)
con.Open()
If cmd.ExecuteNonQuery() = 0 Then
'If no rows are affected then there was not a valid
'record to update, i.e. the student was not logged in
MsgBox("You were not logged in")
Else
MsgBox("You are now logged out!")
End If
End Using
N.B. Please excuse my VB.NET, I have not used it in quite some time so there may be some syntax errors.
So right now I have a listbox that gets data from an access database and prints it out like below:
When the user clicks on "Just Lose It" for example, and then clicks "Remove Song" button, how can I delete that entry from the database and then refresh the list box with the updated table.
I was thinking of creating an SQL DELETE Statement and then use a ADODB.Recordset to run that statement but I'm not sure how to tell the user clicked that entry.
Any ideas?
Use something like the following... add unique key if in hidden column
sqlStr = "DELETE FROM music WHERE [Title] = '" & music_lb.column(0) & "' AND [Artist] = '" & music_lb.column(1) & "' AND [Album] = '" & music_lb.column(2) & "';"
I want to insert OfficerID of the officer currently logged in as a default value into the table T_FileCases.
Already in the login form I have a field that holds officer's name (UserName) when they are logged in successfully but when this happens I also want to automatically insert their OfficerID into the table T_FileCases automatically, instead of using a combo box for selecting officers name when creating a new case.
Me.Hold_User_ID = Nz(DLookup("OfficerID", "Table_Officers", "Names='" & Me.UserName & "' and NRC='" & Me.PWD & "'"), -1)
' check to see if we have a good login
If Me.Hold_User_ID = -1 Then
MsgBox "Sorry boss, you typed invalid username or password.", vbExclamation
Exit Sub
Else
' load the users access level into the holder form field
Me.hold_level = DLookup("Access_Level", "Table_Officers", "Names='" & Me.UserName & "' and NRC='" & Me.PWD & "'")
End If
On the Before Insert event of the data entry form you could create an event procedure to check for the UserID and populate the field with the appropriate value.
This would require that the UserID is able to be retrieved at this point, either by keeping the login form hidden in the background or by assigning the value from the login form to a Global variable at the point of validation.