How to put a concatenated data from database to a label - sql

My table goes like this:
| ID | FNAME | LNAME |
My code goes like this:
cmd.CommandText = "SELECT * FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("CONCAT(fname,' ',lname)").ToString()

cmd.CommandText = "SELECT CONCAT(fname,' ',lname) FROM members WHERE ID = '" & Label18.Text & "';"
Label3.Text = cmd.ExecuteScalar
Note : This makes sense when the select returns a single Cell value
ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or
Stored Procedure and returned a scalar value on first column of first
row in the Result Set. If the Result Set contains more than one
columns or rows , it takes only the first column of first row, all
other values will ignore. If the Result Set is empty it will return a
Null reference.

The easiest way is to just return an additional column from the database itself.
cmd.CommandText = "SELECT *, FullName = fname + ' ' + lname FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("FullName").ToString()

Related

delete selected rowdata in datatable vb

Hey guys how to delete data on datatable
my code where i delete data and the result just remove data from grid not datatable
my current code
selectStr = "AccrualNo = '" & bauAccrual & "' AND GLAccountID = '" & bauGL &"' AND PCCodeID = '" & bauPC & "'"
rowToDelete = TempTable.Select(selectStr)(0)
rowToDelete.Delete
TempTable.AcceptChanges
BAU_grdTransactions.DataSource = TempTable
Try this:
string selectStr = "primary_key =" + pk
DataRow rowToDelete = dataTable.Select(selectStr)(0)
dataTable.Rows.Remove(rowToDelete)
primary_key is the Primary Key of your data table. pk value you can extract from the GridView. if pk is string, use in single quotes.

Receiving an error when attempting to update a record

In my program I have a function titled runSQL, here it is:
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TrainingLog.accdb")
Dim DT As New DataTable
Dim DataAdapter As OleDb.OleDbDataAdapter
Connection.Open()
DataAdapter = New OleDb.OleDbDataAdapter(query, Connection)
DT.Clear()
DataAdapter.Fill(DT)
Connection.Close()
Return DT
And I'm trying to update a record in a database using the update string, sourced from this code:
Dim sqlString As String
sqlString = "UPDATE UserRecords set FirstName = '" & txtName.Text
sqlString = sqlString & "', LastName = '" & txtSurname.Text
If ChkSmoker.Checked = True Then
sqlString = sqlString & "', Smoker = true"
ElseIf ChkSmoker.Checked = False Then
sqlString = sqlString & "', Smoker = false"
End If
sqlString = sqlString & ", Weight = " & txtWeight.Text
If RdoMale.Checked = True Then
sqlString = sqlString & ", Gender = 'm'"
ElseIf RdoFemale.Checked = True Then
sqlString = sqlString & ", Gender = 'f'"
End If
sqlString = sqlString & " WHERE UserName = '" & LstUsers.SelectedItem.ToString & "'"
runSQL(sqlString)
However once I click the save button, I get an error from line 7 of the runSQL function (not including empty line, so that's the DataAdapter.Fill(DT) line) which says "No value given for one or more required parameters."
I wondered if anyone knew why this is or how to fix it.
One thing I did think of is that, in the table being updated, there are fields other than those being mentioned in my UPDATE statement. For example there is a Yes/no field titled "TeamMember", which I don't mention in the update statement.
When using the update function, do I have to give values for every field, even those not being changed?
Thanks for reading, and hopefully helping!
You should never composea SQL query yourself. It much easies and safer (to vaoid SQL injection) to create a parameterized query, or use an stored procedure. And then execute it by pasing the query or stored procedure name and the parameter values.
Besides, in this way, you don't have to take care of what the right format is for a particular value. For example, how do you format a date? And, how do you format a boolean value? Most probably the problem with your query is the false or true value that you're trying to set for the Smoker column, because in TSQL that's a bit value, and can only be 0 or 1.
Check this to see samples of using parameters: ADO.NET Code Examples (Click the VB tab to see it in VB). You'll see that you define a parameter specifying a name with an # prefix in the query, and then you simply pass a value for each parameter in the query, and it will be passed to the server in the correct format without you taking care of it.
Taken from one of the samples:
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > #pricePoint " _
& "ORDER BY UnitPrice DESC;"
Dim command As New SqlCommand(queryString, connection)
command.Parameters.AddWithValue("#pricePoint", paramValue)
'' command.ExecuteXXX
NOTE that you can execute the command in different ways, depending on your need to simply execute it or get an scalar value or a full dataset as a result.

Syntax Error near "name"

conn.Open()
'MsgBox("Established!!!")
cmd.Connection = conn
cmd.CommandText = "SELECT price FROM products WHERE name '" & tb_pname.Text & "'"
dr = cmd.ExecuteReader
While dr.Read
Me.tb_price.Text = Convert.ToString(dr("price"))
End While
conn.Close()
You missed the = equal sign after name
WHERE name = '" & tb_pname.Text & "'"
You are running wrong query. You misses = sign.
Here is correct query
cmd.CommandText = "SELECT price FROM products WHERE name = '" + tb_pname.Text + "'"
If you need the query to not be case-sensitive, you could make a WHERE upper(name) = upper('YourString')
cmd.CommandText = "SELECT price FROM products WHERE upper(name) = upper('" & tb_pname.Text & "')"
You could also use the "like" operator, where you use "WHERE name like 'PutYourTextHere' ", so you can also use wildcards like % for any string.
As an example:
WHERE name like '%Thomson%'
would find any name that contains the string 'Thomson'.
cmd.CommandText = "SELECT price FROM products WHERE name like '" & tb_pname.Text & "'"

Can't insert into acces db with .net

I used this site to get me on my way with the Insert command, however, i can't get it to work.
How can I insert data into 2 different table in VB.net, I'm using MS Access as my db
I got 3 tables, 1 with foodtypes, 1 with (basically) menus and 1 connecting table that connect the id of a menu with the ID's of sfoodtypes.
I try to use a query to create new menu's. however, a error occures:
There is ; missing in the sql string
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Now, i tried different places to place the ; but cant find the right spot. Can anyone help me?
The rest of the code::
EDIT:(and clean-up)
I made some changes based on the comments below, but i still get the ; missing error.
Dim cmd As New OleDbCommand
Dim cmd1 As New OleDbCommand
Dim cmd2 As New OleDbCommand
Dim Str As String
Dim Str1 As String
Dim Str2 As String
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text); " 'WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Str1 = "INSERT INTO tbl_voersoorten (VoerID, Voer) VALUES (cbVoer.text) WHERE Voer = '" & cbVoer.Text & "'"
Str2 = "INSERT INTO tbl_rantsoenKoppel (VoerID, RantsoenID) VALUES() WHERE RantsoenID = tbl_rantsoenkoppel.FKRantsoenID AND VoerID = tbl_voersoorten.VoerID"
connection.Open()
cmd = New OleDbCommand(Str, connection)
cmd1 = New OleDbCommand(Str1, connection)
cmd2 = New OleDbCommand(Str2, connection)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
You can't use WHERE clauses in your INSERT command
and if you want execute more than one command in single CommandTextyou should to seperate them with ;.
and finally:
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES ('" & cbRantsoen.text & "', '"& cbVoer.text & "','"& txtGewicht.text & "')"
Str1 = "INSERT INTO tbl_voersoorten ( Voer) VALUES ('" & cbVoer.text & "')"
and for query Str3 you should to get related id from last two query and insert them into 3th query ;)
Your INSERT Syntax is wrong. There cannot be a WHERE Clause.
INSERT INTO TableName (Column1,Column2,Colum3) VALUES(Value1,Value2,Value3);
If you are trying to change an existing record, try using the UPDATE Clause
UPDATE TableName SET Column1 = Value1 , Column2 = Value2, Column3 = Value3 WHERE Condition1 = Condition2 AND Condition3 = Condition4

Get Result (Number) from an sql query

I want to get a simple result from a SQL query to make some calculation
My code :
cn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = " SELECT shift1 + shift2 + shift3 as shifts FROM Statistique where nom_produit= '" & ComboBox3.Text & "' and p_date like '" & Date1.Text & "' "
cmd.Connection = cn
Dim st As Integer = cmd.ExecuteScalar
MsgBox(st, 0 + 32, "Your Value !")
cn.Close()
The value of "shifts" is what I need. Now I get just 0
Just to make you know, the query executed successfully in MS Access 2007
I suggest you to change your query to make use of a parameterized query. Keep in mind that a date is not a string. Passing a string for the where clause often will result in an incorrect statement
cn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT shift1 + shift2 + shift3 as shifts " & _
"FROM Statistique where nom_produit=? AND p_date = ?"
cmd.Parameters.AddWithValue("#p1", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p2", Date1.Value)
cmd.Connection = cn
Dim st As Integer = cmd.ExecuteScalar
MsgBox(st, 0 + 32, "Your Value !")
cn.Close()
Of course this assumes that your field p_date is a DateTime value in MS-Access and that you type a date and TIME value that could be correctly mapped to the field in the database.
EDIT If Date1 is a DateTimePicker then just use the Value property.
The key point here is to pass a parameter with type equal to the field to which it will be applied.
In this way you don't need to worry about conversions or how do you quote the value in a string concatenation.