sql query how to put 2 "where"condition - sql

first this is the table relationship.
below is what i'm trying to achieve
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName,record_item.Amount FROM record_item,inventory WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "')", conn)
if i'm trying to get ItemName based on the RecordID that i have,do i need to put 2 condition? if i do, how?
WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "') and WHERE(record_item.ItemID=inventory.ItemID)

WHERE (something) AND (something else)

just do:
SELECT inventory.ItemName,record_item.Amount FROM record_item,inventory
WHERE record_item.RecordID = '" & listbox1.SelectedItem & "' and record_item.ItemID=inventory.ItemID

Without second WHERE clause
WHERE
(record_item.RecordID = '" & listbox1.SelectedItem & "')
and (record_item.ItemID=inventory.ItemID)

instead of using two where condition you can use like this
WHERE (1st condition) AND (2nd condition).

Dim ad As New SqlDataAdapter("SELECT inventory.ItemName,record_item.Amount
FROM record_item,inventory WHERE record_item.RecordID = '" & listbox1.SelectedItem & "' AND record_item.ItemID=inventory.ItemID", conn)

Check below code...
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName, record_item.Amount FROM record_item, inventory WHERE (record_item.RecordID = '" & listbox1.SelectedItem & "' AND record_item.ItemID=inventory.ItemID)", conn)
If your record_item.RecordID is Integer, then below query would work...
Dim ad As New SqlDataAdapter("SELECT inventory.ItemName, record_item.Amount FROM record_item, inventory WHERE (record_item.RecordID = " & listbox1.SelectedItem & " AND record_item.ItemID=inventory.ItemID)", conn)

Can't use more than one WHERE in simple SELECT query, either you can use SUBQUERY or other.
in your case, why you are not implement suggested answer.
also you can use IN clause like,
WHERE (record_item.RecordID IN ('" & listbox1.SelectedItem & "', inventory.ItemID )

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

Count data displayed on my datagridview with category

I am having a trouble on counting datas on my datagridview using category i.e. when i filtered my datas by "Department" it shows all data on the same category. But i want to count how many Staffs, Supervisors and Managers are included on that category (Department). I want it to be displayed on my textboxes i.e. txtStaff, tstManagers, txtSups. Thanks you!
Here's my current code :
Try
Dim conF As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0.; Data Source = ..\Database\IRMG TO.accdb")
conF.Open()
Dim query As String
query = "SELECT Employee_Name, P_Level, Position_Title, Department, Team, Subteam1, Subteam2, Immediate_Head, CAREER_BAND, CAREER_ZONE FROM tblEmployees WHERE (" & txtFilterType.Text & " LIKE '%" & txtFilter.Text & "%') "
Dim command As New OleDb.OleDbCommand(query, conF)
Dim adapter As New OleDb.OleDbDataAdapter
Dim dt As New DataTable
adapter.SelectCommand = command
adapter.Fill(dt)
dgvEmployee.DataSource = dt
adapter.Dispose()
command.Dispose()
conF.Close()
Catch ex As Exception
End Try
You might want to do this SQL statement...
query = "SELECT (Select COUNT(Employee_Name) FROM tblEmployees WHERE Position_Title='Staff' AND (" & txtFilterType.Text & " LIKE '%" & txtFilter.Text & "%')) as StaffCount,
(Select COUNT(Employee_Name) FROM tblEmployees WHERE Position_Title='Supervisor' AND (" & txtFilterType.Text & " LIKE '%" & txtFilter.Text & "%')) as SupervisorCount,
(Select COUNT(Employee_Name) FROM tblEmployees WHERE Position_Title='Manager' AND (" & txtFilterType.Text & " LIKE '%" & txtFilter.Text & "%')) as ManagerCount,
Employee_Name, P_Level, Position_Title, Department, Team, Subteam1, Subteam2, Immediate_Head, CAREER_BAND, CAREER_ZONE FROM tblEmployees WHERE (" & txtFilterType.Text & " LIKE '%" & txtFilter.Text & "%')"
Then you VB should go something like this...
adapter.Fill(dt)
txtStaff.Text = dt.Rows(0).Item("StaffCount")
txtSups.Text = dt.Rows(0).Item("SupervisorCount")
tstManagers.Text = dt.Rows(0).Item("ManagerCount")
Don't forget to hide the first 3 columns of your datagridview after it's filled up. You're using the datasource property so everything will come out, just hide them. You'll have more control over your datagridview before it's filled up if you do the loop to display the items than using the datasource directly.
try this.. :
txtResult.Text = dgvEmployee.Rows.Count

Error in my vb but correct in my sql query

Error in my vb but correct in my sql query. Can somebody can correct my VB code.
This is my wrong code in VB
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & Trim(TextBox11.Text.TrimEnd()) & " OR vendorpnumber ='" & Trim(TextBox2.Text.TrimEnd()) & "'", con)
This is my correct code in mysql query
SELECT *
FROM pcba_info.tblvendorpartnumber
WHERE partnumber = '' or vendorpnumber = '';
You must resolved the problem in SQL injections to
You forgot to include the pair of other single quote.
From
TextBox11.Text.TrimEnd()) & " OR
To
Trim(TextBox11.Text.TrimEnd()) & "' OR
To form as
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & TextBox11.Text.Trim().Replace("'", "''") & "' OR vendorpnumber ='" & TextBox2.Text.Trim().Replace("'", "''") & "'", con)
You need to avoid mixing the VB string functions with those of SQL. Write the entire query inside quotes to be certain will work in SQL.
Try like this
Trim will trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".
Dim S1,S2 as String
S1 = TextBox11.Text
S2 = TextBox12.Text
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & S1.Trim & " OR vendorpnumber ='" & S2.Trim & "'", con)

execute multiple command for update vb.net

i am working on a vb project . in this i need to save some record to one table and update some records in another table in one event or click .. i am doing like this .
dim simpan as new sqlcommand
conn = New SqlConnection(connectionstring)
conn.Open()
simpan = New SqlCommand()
simpan.Connection = conn
simpan.CommandType = CommandType.Text
simpan.CommandText = "update barang set (nama_barang,harga)values(" & TextBox3.Text & ",'" & TextBox4.Text & "') where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()
tampil()
MsgBox("Data Berhasil Diubah", MsgBoxStyle.Information, "Informasi")
conn.Close()
but it giving error as "incorrect syntax near '('" .. i am not getting where i go wrong .. please help me
I see a couple issues with this...
Your Syntax is wrong on your update statement (Al-3sli beat me to that one).
Your textbox values will cause issues if a user types a single quote in the text box (For Example: The word "Wasn't".
Add the replace function to each textbox TextBox3.text.Replace("'","''") That will replace single ticks with two single ticks.
You might also consider using parameterized queries
You can't use update like this, change your code like so:
simpan.CommandText = "update barang set nama_barang = '" & TextBox3.Text & "',harga ='" & TextBox4.Text & "' where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()

check the update command, m i doing mistake in its syntax?

his there all,
i'm working on a cms, while trying the update command to update the records, its not working.
here's m complete code for update,
Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone, CheckupDate, Disease, BloodGroup, Doctor, Remarks As String
RegNo = txtRegNo.Text
BedNo = CmbBedNo.SelectedItem.ToString()
BedType = CmbBedType.SelectedItem.ToString()
Charges = txtCharges.Text
PatName = txtPatName.Text
PatAge = txtPatAge.Text
PatAddr = txtPatAdd.Text
Phone = txtPhone.Text
CheckupDate = txtDate.Text
Disease = txtDisease.Text
BloodGroup = cmbBloodGrp.SelectedItem.ToString()
Doctor = cmbDoctor.SelectedItem.ToString()
Remarks = txtRemarks.Text
ID = txtRegNo.Text
Dim conStudent As New OleDbConnection
Dim comStudent As New OleDbCommand
conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
conStudent.Open()
comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ", Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" & Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ", Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" & CheckupDate & "', Disease='" & Disease & "', BloodGroup='" & BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "' WHERE ID=" & RegNo
comStudent.Connection = conStudent
comStudent.CommandType = CommandType.Text
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
conStudent.Close()
one thing, that the fields named with ID, BedNo, BedCharges, Age are set to Number as data type.
First of all, switch to a parameterized query. This will remove any possibilities of Sql Injection, but also avoid the problems with quoting strings, parsing decimal numbers and dates
Dim conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
Dim cmdText = "UPDATE AdmitPt SET ID =?, Bedcategory=?, BedNo=?, BedCharges=?, " & _
"PtName=?, PtAge=?, Address=?, PhoneNo=?, Dates=?, Disease=?, " & _
"BloodGroup=?, Doctor=?, Remarks=? WHERE ID=?"
Using conStudent = new OleDbConnection(conString)
Using comStudent = new OleDbCommand(cmdText, conStudent)
conStudent.Open()
comStudent.Parameters.AddWithValue("#p1", Convert.ToInt32(ID))
comStudent.Parameters.AddWithValue("#p2", BedType)
comStudent.Parameters.AddWithValue("#p3", Convert.ToInt32(BedNo))
comStudent.Parameters.AddWithValue("#p4", Convert.ToDecimal(Charges))
.... and so on for every other question marks in the cmdText ....
.... respecting the exact order of the fields ...................
.... try also to pass the correct datatype for every non string field
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
End Using
End Using