select and update query first row in a column - vb.net

this is my select query, i was able to retrieve in a textbox. but when i updating, it updates all of its record in first column and i know that the reason is the 'ExecuteScalar', so anyone knows what should i replace in this? because i only want to update first row in a column?
Dim fname As New SqlCommand
Dim lname As New SqlCommand
Dim CMD As New SqlCommand
con = New SqlConnection("server=;uid=admin;pwd=t;database=")
con.Open()
fname = New SqlCommand("select first_name from employee_info where employee_id='" & TextBox1.Text & "';", con)
lname = New SqlCommand("select last_name from employee_info where employee_id='" & TextBox1.Text & "';", con)
CMD.Connection = con
TextBox3.Text = fname.ExecuteScalar
fname.ExecuteNonQuery()
TextBox4.Text = lname.ExecuteScalar
lname.ExecuteNonQuery()
by the way this is my update query....
fname = New SqlCommand("UPDATE employee_info SET first_name= '" & TextBox3.Text & "';", con)
fname.Connection = con
fname.ExecuteNonQuery()
lname = New SqlCommand("UPDATE employee_info SET last_name= '" & TextBox4.Text & "';", con)
lname.Connection = con
lname.ExecuteNonQuery()

Because you didn't specify which row you want to update. For example;-
fname = New SqlCommand("UPDATE employee_info SET first_name= '" & TextBox3.Text & "' WHERE [columnName]= '[columnValue]'", con)
fname.Connection = con fname.ExecuteNonQuery()

Related

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

Combining two Columns

I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename.
I have tried this code
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', CONCATE(Textbox2.text, ',', Textbox3.Text))"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
The section CONCATINATE will be like the following:
"CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))"
But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types.
Example:
Dim query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (" & _
"#adm,#fName,#mName,CONCATE(#fNameC,',',#mNameC))"
Dim cmd As New SqlCommand(query, cn)
cmd.Parameters.Add("#adm", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mName", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#fNameC", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mNameC", SqlDbType.VarChar).Value = TextBox3.Text
'Execute the query here
Before query first store two textbox value in one variable
cn.Open()
Dim query As String
Dim fullname As String
fullname = TextBox1.text + "" + TextBox2.text
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & fullname & '")"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
You can concatenate with String.Concat, and I advice you to use the Parameter to avoid sql injections, like this :
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", TextBox2.Text))
cmd.Parameters.Add(New SqlParameter("#MiddleName", TextBox3.Text))
cmd.Parameters.Add(New SqlParameter("#FullName", String.Concat(TextBox2.Text, ",", TextBox3.Text)))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Save the Firstname and Middlename values into variables and concat() them together before sending to the query.
cn.Open()
Dim query As String
Dim firstname As String
Dim middlename As String
Dim fullname As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
firstname = TextBox2.Text
middlename = TextBox3.Text
fullname = String.Concat(firstname, ",", middlename)
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", firstname))
cmd.Parameters.Add(New SqlParameter("#MiddleName",middlename))
cmd.Parameters.Add(New SqlParameter("#FullName", fullname))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Note that the query builder has been reformatted to remove vulnerability to SQL injection.
Use following line instead of your.
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & Textbox2.Text & " " & Textbox3.Text & "')"

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

Copy the contents(including headers) of a ListView to a DataGridView in VB.net

I have a ListView that has values from a database. I used two MS Access OLEDB Statements to produce the data I have. So I used two While Loops. The second OLEDB Statement is with reference to the first. How do I insert all the contents of my ListView to a DataGridView?
Here is my code for the two While loops that is used to call out the OLEDB Statements:
Dim connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\STSlog.mdb;Jet OLEDB:Database Password=password;"
Dim conn As New OleDbConnection(connectionstring)
Dim command, command2, command3 As New OleDbCommand
Dim commstring, commstring2, commstring3 As String
Dim searchstring As String
commstring = "SELECT DISTINCT empname FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' ORDER BY empname ASC"
command = New OleDbCommand(commstring, conn)
commstring3 = "SELECT SUM([Regular]) AS sRegular, SUM(OT) AS sOT FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command3 = New OleDbCommand(commstring3, conn)
MainLView.Clear()
MainLView.GridLines = True
MainLView.FullRowSelect = True
MainLView.View = View.Details
MainLView.MultiSelect = True
MainLView.Columns.Add("Employee Name", 290)
MainLView.Columns.Add("Total Regular", 200)
MainLView.Columns.Add("Total Overtime", 200)
MainLView.Columns.Add("Total Hours", 200)
conn.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim RegSum, OTSum, Total As Decimal
While reader.Read
searchstring = reader("empname")
commstring2 = "SELECT SUM([Regular]) AS sReg, SUM(OT) AS sOT FROM data WHERE empname = '" & searchstring & "' AND ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command2 = New OleDbCommand(commstring2, conn)
Dim reader2 As OleDbDataReader = command2.ExecuteReader()
While reader2.Read
RegSum = (reader2("sReg"))
OTSum = (reader2("sOT"))
Total = Format((RegSum + OTSum), "0.0")
With MainLView.Items.Add(reader("empname"))
.subitems.add(reader2("sReg"))
.subitems.add(reader2("sOT"))
.subitems.add(Total)
End With
End While
End While
I added columns first to my DataGridView then inserted the data from the database using DataGridView Rows.
Dim connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\STSlog.mdb;Jet OLEDB:Database Password=password;"
Dim conn As New OleDbConnection(connectionstring)
Dim command, command2, command3 As New OleDbCommand
Dim commstring, commstring2, commstring3 As String
Dim searchstring As String
commstring = "SELECT DISTINCT empname FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' ORDER BY empname ASC"
command = New OleDbCommand(commstring, conn)
commstring3 = "SELECT SUM([Regular]) AS sRegular, SUM(OT) AS sOT FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command3 = New OleDbCommand(commstring3, conn)
MainLView.Clear()
MainLView.GridLines = True
MainLView.FullRowSelect = True
MainLView.View = View.Details
MainLView.MultiSelect = True
MainLView.Columns.Add("Employee Name", 290)
MainLView.Columns.Add("Total Regular", 200)
MainLView.Columns.Add("Total Overtime", 200)
MainLView.Columns.Add("Total Hours", 200)
Dim col1 As New DataGridViewTextBoxColumn
Dim col2 As New DataGridViewTextBoxColumn
Dim col3 As New DataGridViewTextBoxColumn
Dim col4 As New DataGridViewTextBoxColumn
col1.HeaderText = "Employee Name"
col2.HeaderText = "Total Regular"
col3.HeaderText = "Total Overtime"
col4.HeaderText = "Total Hours"
ReportDGV.Columns.Add(col1)
ReportDGV.Columns.Add(col2)
ReportDGV.Columns.Add(col3)
ReportDGV.Columns.Add(col4)
conn.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim RegSum, OTSum, Total As Decimal
While reader.Read
searchstring = reader("empname")
commstring2 = "SELECT SUM([Regular]) AS sReg, SUM(OT) AS sOT FROM data WHERE empname = '" & searchstring & "' AND ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command2 = New OleDbCommand(commstring2, conn)
Dim reader2 As OleDbDataReader = command2.ExecuteReader()
While reader2.Read
RegSum = (reader2("sReg"))
OTSum = (reader2("sOT"))
Total = Format((RegSum + OTSum), "0.0")
With MainLView.Items.Add(reader("empname"))
.subitems.add(reader2("sReg"))
.subitems.add(reader2("sOT"))
.subitems.add(Total)
Dim row As String() = New String() {reader("empname"), reader2("sReg"), reader2("sOT"), Total}
ReportDGV.Rows.Add(row)
End With
End While
End While

how to use multiple combo boxes to filter data

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.
you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.