Display SQL Result in label? - sql

Dim invoiceCount As String =
"SELECT COUNT(CustomerID) " &
"FROM Invoices " &
"WHERE CustomerID = #customerID"
Dim selectCount As New OleDbCommand(invoiceCount, connection)
selectCount.Parameters.AddWithValue("#customerID", customerID)
Try
connection.Open()
Dim reader2 As OleDbDataReader = selectCount.ExecuteReader(CommandBehavior.SingleRow)
If reader2.Read Then
frmCustomerMaintenance.lblIncidents.Text = 'what do I put here?
End If
reader2.Close()
Catch ex As OleDbException : Throw ex
Finally : connection.Close()
End Try
I've been messing with this for a while now and everything I try returns an error. I'm still fairly new to SQL in general but this needs to be done. I just want to store the result of the query in a label to show how many records the customer entered has..

Well, to read the first column, you can just do this:
frmCustomerMaintenance.lblIncidents.Text = reader.GetValue(0).ToString()
However, when you are only reading a single column from a single row, like that, it's easier to just call ExecuteScalar instead of ExecuteReader:
frmCustomerMaintenance.lblIncidents.Text = selectCount.ExecuteScalar().ToString()

This is what you are searching for:
frmCustomerMaintenance.lblIncidents.Text = reader2[0].ToString()

Related

get last inserted primary key record in database

Please help to get the primary key of the last insert record as the one which i have gives me duplicate rows in the database and return 0
Try
If Conn.State = ConnectionState.Open Then Conn.Close()
'insert the new customer data
Conn.Open()
cmd = New SqlCommand("insert into Quote values ('" & dateOFCreat & "','" & Emp & "','" & Customer_no & "' )", Conn)
Dim a As Integer = cmd.ExecuteNonQuery()
Dim results As Integer
Dim cmd_results As SqlCommand
'Get the last created Quote in the Database
cmd_results = New SqlCommand("Select ##Identity from Quote", Conn)
results = cmd.ExecuteScalar
TxtLastQuoteID.Text = results
If a = 0 Then
MsgBox("Error")
End If
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
You can make use of the batch commands supported by Sql Server. Just put together the two instructions and just use ExecuteScalar. However, before that, you need to fix ASAP your Sql Injection vulnerability. Do not concatenate strings to build an sql command, but use parameters.
Try
Using con as SqlConnection = new SqlConnection(....constringhere...)
Conn.Open()
Dim sqlText = "insert into Quote values (#dat,#emp,#cusno); SELECT SCOPE_IDENTITY()"
cmd = New SqlCommand(sqlText,Conn)
cmd.Parameters.Add("#dat", SqlDbType.NVarChar).Value = dateOFCreat
cmd.Parameters.Add("#end", SqlDbType.NVarChar).Value = emp
cmd.Parameters.Add("#cusno", SqlDbType.NVarChar).Value = Customer_no
Dim lastID As Integer = cmd.ExecuteScalar()
TxtLastQuoteID.Text = lastID.ToString()
Conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Notice also that is a very bad thing to keep a global connection object. You don't need that because ADO.NET implements Connection Pooling that makes opening a connection a very fast operation. Instead keeping a connection around requires a lot of effort to work correctly around it
Finally you can look here to better understand the difference between SCOPE_IDENTITY and ##IDENTITY and why is usually better to use the first one.

Validate SQL data and check for Null

I have a textbox(txtOrderNum) where you enter an 'order' number and update a 'userfield' based on a date that is generated in another textbox(txtDate), I want to validate that the 'order' number entered matches the 'Order' number in the database, then update 'UserField1' only if its NULL, if it doesn't match then do nothing.
My goal, I don't want to overwrite data that is already in the Userfield1, and I want to ensure I update the correct 'Order' number that exist.
****I've updated my code based on suggestion below, I just need to validate if 'Order' number exist AND matches the order number entered in the textbox, then run update query. (also need to parameterized the query, I have some ideas but could use some help)****
Public Sub executequery(ByVal query As String)
Try
Dim cmd As New SqlCommand(query, conn)
conn.Open()
If (conn.State = ConnectionState.Open) Then
cmd.ExecuteNonQuery()
conn.Close()
Else
MessageBox.Show("Check Connection")
conn.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
Finally
conn.Close()
End Try
End Sub
'My call Event via Enter Key within Textbox (txtOrdernum)
Dim conn As New SqlConnection("My data source")
Try
Dim updatequery As String = ("UPDATE [DATA].[dbo].[Order] SET [Userfield1] = '" & txtDate.Text.Trim() & "' WHERE [order] ='" & txtOrdernum.Text.Trim() & "' AND [Userfield1] IS NULL")
If e.KeyChar = Chr(13) Then 'Chr(13)
If txtOrdernum.Text.Length >= 8 Then
'MessageBox.Show(updatequery)
executequery(updatequery)
Else
MessageBox.Show("Invalid Order Number'")
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
End Try
As N0Alias stated, add "AND [UserField1] IS NULL".
Just be careful with the way you build your query. Building one like your example can allow SQL injection.
You should use the 'SqlCommand.Parameters' property to add values into your query.

I want to display records in my textbox

When i input the id number of the student in my TextBox, i want the details of that particular students to be displayed in my textbox, without using datagrid. i am using vb.net.
That is my code and i don't understand what's wrong:
cmd.CommandText = "SELECT * from tblsupplier where pro_code = '" & txcode.Text & "'"
dr = cmd.ExecuteReader
txname.Text = dr.item("sup_product")
txprice.Text = dr.Item("sup_price")
First off, you have left your application open to sql injection by adding the value of the textbox inline. Look up this topic please:
http://en.wikipedia.org/wiki/SQL_injection
As for your code, you need to call dr.Read() before you can actually access any properties from your query.
while (dr.Read()) {
// Do stuff
}
Good luck!
It would help if you could provide additional details about the error, friend. Like what SQL you are using, what was the error message, and which event triggers this reader command.
As it stands, it seems you haven't really sent the DataReader to scan the database. You need the While reader.read() loop.
Here is an example, using OLEDB in a function that fetches the data
Note that connstring is my SQL connection string to an Access Database
Dim conn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=MyDatabase.mdb;Jet OLEDB:Database Password=;")
Function Mycheckifexistss(ByVal sqlCMDstring As String)
Dim sqlCmd As New OLEDBCommand(sqlCMDstring, conn)
Dim reader As OLEDBDataReader
Dim result As String = ""
Try
conn.Open()
reader = sqlcmd.ExecuteReader
While reader.Read
result = reader(0) 'this returns the first field of the queried result.
End While
conn.Close()
Return result
Catch ex As Exception
conn.Close() 'the first thing you want to do in an error, is to close the connection first.
MsgBox(ex.ToString)
End Try
End Function

How can I filter without redundant display to combobox?

hmm this is my problem, How can I prevent double display in my Combobox if i have a datatable
"Student" with column "Section" inside is BE701P, BE101P, BE701P, BE701P, BE101P.
I want to display only to combobox the "BE701P and BE101P" like this preventing redundant display, is it possible?
Private Sub section()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT [section] FROM student where username like'" & Administrator.lblusername.Text & "%' ")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "section"
cmbsection.DataSource = ds.Tables(0)
cmbsection.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
it will display all data into combobox and makes redundant display. as i want to prevent redundancy. I would be very glad to any suggestions.
Why not use DISTINCT in your sql query like:
Dim sSQL As String = ("SELECT DISTINCT [section] FROM student
where username like'" & Administrator.lblusername.Text & "%' ")
See link here for mysql examples (although you did not specify your DBMS).
You can create a DataTable from the default DataView of your DataTable that show distinct records only. The advantage of using this approach is that you can keep all records in your original DataTable (which may be used for some other binding). Also note that this is a client-side operation, so you can save your server some processing effort if there are many clients doing this.
The syntax would be something like:
ds.Tables(0).DefaultView.ToTable(True, {"section"})

the user must match to the 3 fields

Dim elem As String
elem = "Grade School"
Dim v As Integer
v = 0
Dim con As New SqlConnection("SERVER=ANINGDZTS-PC;DATABASE=AEVS;Trusted_Connection = yes;")
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department, VotersID = '" & elem & "''" & txt_PwordElem.Text & "'AND Voted ='" & v & "'", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
Try
If (sdr.Read() = False) Then
high()
Else
MessageBox.Show("WELCOME!")
elemBallot.Show()
Me.Hide()
End If
Catch EX As Exception
MsgBox(EX.Message)
End Try
End Sub
this code is not working, an error appear," An expression of non-boolean type specified in a context where a condition is expected, near ','."
Instead of trying to create your SQL query via concatenating strings, which is prone to errors, a much better way is to use parametrized query. Change your SqlCommand declaration to
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department = #Department AND VotersID = #VotersID AND Voted = #Voted", con)
cmd.Parameters.AddWithValue("#Department", elem)
cmd.Parameters.AddWithValue("#VotersID", txt_PwordElem.Text)
cmd.Parameters.AddWithValue("#Voted", v)
Bonus: Avoid SQL Injection
P.S. Please don't forget to close your Reader and Connection after the use.
P.P.S. If you simple need to make sure that specific row in table "tbl_Voter" exists or not based on your parameters (which is, judging by the code what you're doing) - using DataReader is overkill. Consider query like SELECT 1 FROM tbl_Voter ... and use of ExecuteScalar to check returned value for Nothing