Show last row of database MySQL VB.net - mysql

How can I show the last row of data in database?
I have this code here but it only shows the first data row in database
Dim cnPodaci AsNew SqlConnection
cnPodaci.ConnectionString = "your connection string"
cnPodaci.Open()
Dim cm AsNew SqlCommand
cm.CommandText = "SELECT * FROM TABLE"
cm.Connection = cnPodaci
Dim dr As SqlDataReader
dr = cm.ExecuteReader
If dr.HasRows Then
dr.Read()
txtBox1.text = dr.Item("ColumnName1")
txtBox2.text = dr.Item("ColumnName2")
dr.Close()
EndIf
cnPodaci.Close()

You may add an "ORDER BY" to your sql. Like
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc"
Assuming XX is the name of the column which increases for every new row.
Edit:
consider:
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc limit 1"
It will return the last row, having chosen what XX is.

Related

How to select on junction table depending on student ID

first sorry my english is bad.
I am having a problem using junction table it only return me 1 subject this is my query.
I have a
Student_tbl, Subject_tbl , student_subject_tbl the junction table.
And this is my query i am using vb.net
SELECT subject_name
FROM student_subject
JOIN student ON student.StudentID = student_subject.student_id
JOIN subject_bsit ON subject_bsit.subject_id = student_subject.sub_id
WHERE student.StudentID='" & TextBox1.Text & "'"
What i want to do is i just want to select all subject name that is belong to the student_id student id is equals to my textbox in vb.net that is where i will type the student id of student. THank you so much.
EDIT:
I am trying to display the value of all subject name of the entered student id on the textbox. this is my vb.code on displaying it only display the first subject on subject_tbl
cmd = New MySqlCommand(sql, myconn)
dr = cmd.ExecuteReader
If dr.Read = True Then
TextBox2.Text = dr(0)
'Label4.Text = dr(1)
TextBox4.Text = dr(1)
TextBox5.Text = dr(2)
TextBox6.Text = dr(3)
TextBox7.Text = dr(4)
TextBox8.Text = dr(5)
dr.Close()
You don't have to Join with Students table, since the Id's are stored in the junction table also and you are not retrieving student information, also use parameterized command instead of building the command manually to avoid SQL injection.
Try using the following code:
Dim strQuery as string = "SELECT subject_name " & _
" FROM student_subject " & _
" INNER JOIN subject_bsit ON subject_bsit.subject_id = student_subject.sub_id" & _
" WHERE student_subject.student_id = #StudentID"
Dim cmd as New MySqlCommand(strQuery,connection)
cmd.AddParameterWithValue("#StudentID",Textbox1.text)
cmd.ExecuteReader()
Update 1
The index you pass to the datareader object is the column index not the row index, also you have to use a loop instead of an if condition:
cmd = New MySqlCommand(sql, myconn)
dr = cmd.ExecuteReader()
While dr.Read = True Then
Msgbox(dr(0).Tostring())
End While
dr.Close()
Update 2 - passing textboxes name dynamically
First, you have to make sure that the number of textboxes is less than or equal to the number of rows returned.
cmd = New MySqlCommand(sql, myconn)
dr = cmd.ExecuteReader()
Dim cnt as Integer = 1
While dr.Read = True Then
Dim txt As New TextBox = DirectCast(Me.Controls.Find(string.Format("Textbox{0}", cnt ),false).FirstOrDefault(),Textbox);
txt.Text = dr(0).ToString()
cnt += 1
End While
dr.Close()
But Why not showing results in a GridView??

VB.NET MySQL - datatable returns blank row while db has no data

I am trying to search a data in my MySQL table...
Dim cmd As New MySqlCommand
Dim qry As String = "SELECT SUM(amt) FROM fee_payment WHERE roll_no='" + st_roll + "' AND course='" + c_id + "'"
cmd.Connection = conn
cmd.CommandText = qry
Dim dt As New DataTable
Dim dadapter As New MySqlDataAdapter
dadapter.SelectCommand = cmd
dadapter.Fill(dt)
If dt.Rows.Count > 0 Then
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
Dim t_paid = dr("SUM(amt)")
TbDue.Text = tot_fees - t_paid
End While
dr.Close()
End If
Surprisingly the above dt.Rows.Count returns 1 while the table fee_payment has no data.
What should I do ??
There is nothing surprising at all about the result.
An aggregation query with no group by always returns one row. If all rows are filtered out, then most aggregation functions return NULL, although COUNT() and COUNT(DISTINCT) return 0.
This is standard behavior and how all databases work. It is actually quite a convenience under some circumstances.
EDIT:
If you wanted behavior where no rows are returned, just add a group by:
SELECT SUM(amt)
FROM fee_payment
WHERE roll_no = '" + st_roll + "' AND course = '" + c_id + "'
GROUP BY roll_no, course;

Selecting records in table of SQL Server

I'm learning SQL Server and VB.NET. My problem is how to select and make a condition to specific row in the table.
Like, that I have table with two columns name, age, and I want to select rows where name is "XY".
After that, make a condition with an (if) statement like: if age (in the table) larger than 20.
Do some thing or each one his name "xy" print his age in a messagebox.
You can try this in one query like this:
select * from yourtable where name = 'XY' and age > 20
Noor, Rahul was exactly correct in what was recommended. It sounds like you have little experience with how to get data from a SQL query into a useable form so you can test and manipulate or analyze data. For technology, look at ADO, and ADOX usage in VB.NET with SQL queries. My recommendation is for you to purchase one or more good books on VB.NET, so you can fully understand how to move forward.
Dim filename As String = "C:\myfile.mdb"
Dim tablename as String = "mytable"
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data source =" & filename
Dim cn As New OleDbConnection(ConnString)
cn.Open()
Dim qry As String
Dim cmd As New OleDbCommand(qry, cn)
qry = "SELECT * FROM [" & tablename & "] WHERE name = "XY" and age > 20 ORDER by age "
cmd.CommandText = qry
cmd.Connection = cn
Dim drdata As OleDbDataReader = cmd.ExecuteReader
Dim Cnt As Integer = 0
Dim name(), age() as Object
Do While drdata.Read
Cnt += 1
Redim Preserve name(Cnt)
Redim Preserve age(Cnt)
name(Cnt) = drdata.Item("name")
age(Cnt) = drdata.Item("age")
Loop
drdata.Close()
For i As Integer = 1 to Cnt
If age(i) = 20 Then
' do anything you want here
End If
Next i

How do I generate a new Primary Key ID through code?

So basically I'm trying to write the below code to the database and I have the primary key as an Int and it was autogen but when writing to the database it didnt allow me to do it kept telling me that I wasn't allowed to enter a null value (because the code is obviously not writing to the primary key field) so I used the line
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
But the problem is I have to change the value each time I want to test a new record i.e. 1,2,3,4 and so on. I was wondering is there a line of code I can put in to make it create a value by adding +1 each time so I don't need to go into the code and enter a new number each time. Below is the full code writing to the database so you can see a better view of it
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventID, EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress) Values(#EventID, #EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
cmd.Parameters.Add("#EventName", SqlDbType.Text).Value = EventNametxt.Text
cmd.Parameters.Add("#VenueName", SqlDbType.Text).Value = VenueLoDD.SelectedValue
cmd.Parameters.Add("#NumberOfGuests", SqlDbType.Int).Value = CInt(NumOfGtxt.Text)
cmd.Parameters.Add("#Date", SqlDbType.Int).Value = CInt(DateTxt.Text)
cmd.Parameters.Add("#ClientAddress", SqlDbType.Text).Value = txtAddress.Text
cmd.Parameters.Add("#WeddingName", SqlDbType.Text).Value = txtWedding.Text
cmd.Parameters.Add("#BuildingAddress", SqlDbType.Text).Value = txtBAddress.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
If your EventID is an IDENTITY column, you should never try to set a value for it.
Just ignore that field both as parameter or inside the INSERT command.
And you can retrieve the value assigned by the database engine to your field in this way
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "INSERT [Event Table] " & _
"(EventTypeID, EventName, VenueName, NumberOfGuests, [Date], ClientAddress, " & _
"WeddingName, BuildingAddress) Values(#EventTypeID, #EventName, #VenueName, " & _
"#NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress); " & _
"SELECT SCOPE_IDENTITY()"
Using Con = New SqlConnection(".....")
Using cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
.....
Con.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim newEventID = Convert.ToInt32(result)
....
End If
End Using
End Using
With this code you don't pass anything for the EventID field but you add a second command text to your query. This second command will return the last value generated for an IDENTITY column by the database for your connection. This double command (A.K.A. batch commands) is executed using ExecuteScalar because we are interested in the single value returned by the SELECT SCOPE_IDENTIY()
Notice also that DATE is a reserved word in T-SQL so it is possible to use it as name of a column only if you enclose it in square brackets

insert multiple data mysql using for loop

This is the scenario, I have a select query then all fetched data must be inserted into another table.. This is what I came up, I don't know if the for loop does anything.
If I would remove the for loop.
Example:
Fetched data is id1, id2, id3
the inserted data in my database is id1, id1, id1 instead of id1, id2, id3
sql = "SELECT * FROM dummy_violate WHERE res_month <> #month Or res_year <> #year"
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
dr = cmd.ExecuteReader
While dr.Read
id += dr(0)
count += 1
End While
dr.Close()
If count > 0 Then
For i As Integer = 1 To count
sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid)VALUES(#id,#month,#year,#paid)"
cmd = New MySqlCommand(sql2, con)
cmd.Parameters.AddWithValue("#id", id)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
cmd.Parameters.AddWithValue("#paid", 0)
cmd.ExecuteNonQuery()
Next
ElseIf count = 0 Then
MsgBox("Wrong Query")
End If
I don't really understand what you are trying to do and why, it seems that you are simply duplicating the records already present in your table with new records with the same data but with the is_paid flag set to zero. If so just try changing your code in this way:
sql = "SELECT res_id FROM dummy_violate WHERE res_month <> #month Or res_year <> #year"
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
Dim da = new MySqlDataAdapter(cmd)
Dim dt = new DataTable()
da.Fill(dt)
' if we have records to duplicate we have Rows.Count > 0
If dt.Rows.Count > 0 Then
sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid) " & _
"VALUES(#id,#month,#year,#paid)"
cmd = New MySqlCommand(sql2, con)
' Add all the parameters before entering the loop. Just #id changes for every loop,
' so we set it with a dummy value outside the loop and we change it when looping over
' the result table.....
cmd.Parameters.AddWithValue("#id", 0)
cmd.Parameters.AddWithValue("#month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("#year", DateTime.Now.ToString("yyyy"))
cmd.Parameters.AddWithValue("#paid", 0)
' execute the insert for all the rows count
' rows array starts at zero so loop to count -1
For i As Integer = 0 To dt.Rows.Count - 1
cmd.Parameters("#id").Value = dt.Rows(i)("res_id")
cmd.ExecuteNonQuery()
Next
ElseIf count = 0 Then
MsgBox("Wrong Query")
End If
Remember that if the res_id is a primary key then you cannot insert the records with the same res_id twice. Also, if res_id is an auto_number column (a.k.a. IDENTITY) then you cannot explicitily set its value