VB.NET:Updating record in Ms Access - vb.net

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.

As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

Related

Count no. of Rows on my Database table Between the selection of two Datetimepicker

How can I get the total Rows of date records on my database between the selection of two datetimepicker? I don't have any idea how to do this. Had been searching for an answer for about an hour but I cannot find the correct code. Please help me.
Here's my code:
Try
ConnDB()
If fromDate.Value > toDate.Value Then
MessageBox.Show("Invalid Date Selection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN='" & fromDate.Value.ToShortDateString & "' AND '" & toDate.Value.ToShortDateString & "'"
da = New OleDbDataAdapter(sqlqry, cnn)
Dim dt As New DataTable("tblAttendance")
da.Fill(dt)
dgvAttendance.DataSource = dt
Dim counter As Double
counter = dt.Rows.Count
TextBox1.Text = counter
End If
Catch ex As Exception
If cnn.State = ConnectionState.Open Then
cnn.Close()
End If
End Try
It only shows 0 value if I qoute as a comment this part of the code:
da = New OleDbDataAdapter(sqlqry, cnn)
Dim dt As New DataTable("tblAttendance")
da.Fill(dt)
dgvAttendance.DataSource = dt
You must format the string expressions of the date values to fit Access SQL:
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN #" & fromDate.Value.ToString("yyyy'/'MM'/dd") & "# AND #" & toDate.Value.ToString("yyyy'/'MM'/dd") & "#"
or use parameters as already suggested.
Finally figured out, Thanks for the help.
Here's my new code which really works.
Try
ConnDB()
If fromDate.Value > toDate.Value Then
MessageBox.Show("Invalid Date Selection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN #" & fromDate.Value & "# AND #" & toDate.Value & "#"
da = New OleDbDataAdapter(sqlqry, cnn)
dt = New DataTable("tblAttendance")
da.Fill(dt)
Dim counter As Integer
counter = dt.Rows.Count
TextBox1.Text = counter
End If
Catch ex As Exception
If cnn.State = ConnectionState.Open Then
cnn.Close()
End If
End Try

SQL Error: "There are no rows at position 0"

I am Trying to create a login form for my software and i keep getting this feedback as error; "There are no rows at postion 0".....This happens whenever i try to add a WHERE clause to my (SLELECT ProfileName, ProfilePassword from Profile) query (i.e 'sqlQuery' in code)......This is a snippet of my code
Public Sub sql_login(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'INITIALIZE YOUR COMMANDS
'IT HOLDS THE DATA TO BE EXECUTED
With cmd
'PASS ON THE VALUE OF CON TO THE MYSQL COMMANND WHICH IS THE CONNECTION
.Connection = con
'THE FUNCTION OF THIS IS TO RETURN THE TEXT REPRESENTED BY A COMMAND OBJECT
.CommandText = sqlQuery
End With
Dim dt = New DataTable
'FOR RETRIEVING AND FILLING DATA IN THE TABLE
Dim da = New SqlDataAdapter(sqlQuery, con)
'NEW TABLE IN THE DATATABLE
da.Fill(dt)
con.Close()
'SET THE TOTAL ROWS OF THE TABLE IN A VARIABLE[MAXROWS]
Dim maxrows As Integer = dt.Rows.Count
con.Close()
'preventing non empty values
If Loginform.UsernameTextBox.Text <> "" And Loginform.PasswordTextBox.Text <> "" Then
If dt IsNot Nothing Then
'CHECKING IF THE TOTAL ROWS OF THE TABLE ARE GREATER THAN 0
If maxrows > 0 Then
'THIS WILL BE NOTIFY YOU THAT WHO WOULD BE THE USER'S
MessageBox.Show("Welcome " & dt.Rows(1).Item(0) & "!" & ControlChars.NewLine & "You have sucessfully logged in.", "Login Confirmation")
'Tracing login time
Try
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT INTO ProfileDates (ProfileName, LoginDates, ProfileID) VALUES ('" & Loginform.UsernameTextBox.Text & "',GetDate(),( SELECT TOP 1 profileID FROM Profile where ProfileName = '" & Loginform.UsernameTextBox.Text & "') )"
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Suppliers_Module.LogoutBtn.Enabled = True
Suppliers_Module.LoginButton.Enabled = False
Catch ex As Exception
con.Close()
MessageBox.Show(ex.Message)
End Try
end if
end if
end if
counting on you for your help. Thanks in advance!

error 'There is already an open DataReader associated with this Command which must be closed first.'

I use below code but it gives error on sentence icount = cmd.ExecuteNonQuery
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Try always calling the Close method when you have finished using the DataReader object.
dr1.Close();
Another optionis to turn on MARS , in your connection string just add "MultipleActiveResultSets=True;"
Try this:
Try
insert data in combobox
cmd.Connection = con
cmd.CommandText = "select name from party"
dr = cmd.ExecuteReader()
cb_ms.Items.Add("---Select---")
cb_ms.SelectedIndex = 0
While dr.Read() 'get error here.'
cb_ms.Items.Add(dr("name"))
End While
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You could just close the datareader before the 2nd query, but it's better still to get this all into a single query in the first place. Moreover, you really need to close that awful sql injection issue.
Try this to fix both issues:
Dim sql As String = _
"IF NOT EXISTS
(
SELECT 1 FROM [SchoolERP].[dbo].[caste] where (caste = #caste )
)
BEGIN
INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES( #caste)
END"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Use actual columnn type from the database here
cmd.Parameters.Add("#caste", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cn.Open()
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
End Using
Use Try.. Catch.. Finally... End Try somehing like this:
Try
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Catch error As Exception
........
Finally
dr1.Close
End Try
I got Answer ... i only close connection before icount = cmd.ExecuteNonQuery this sentence and again open connection...and its works..
thanks disha..

count max records in web service

I want to count max records called srno from table called complaint in a database. How to write it in web service?
I am using this code
'open
Dim cmd18 As OleDbCommand
Try
'MsgBox("open")
cnn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\CRM.mdb")
cnn.Open()
msg = "select count(srno) from [Complaint] where [status]= '" & Me.RadButton6.Text & "'"
cmd18 = New OleDbCommand(msg, cnn)
str = cmd18.ExecuteScalar()
Catch ex As Exception
' MsgBox("No Records Inserted" + ex.ToString())
Finally
cnn.Close()
End Try
If str Is DBNull.Value Then
Button1.Text = "0"
Else
Button1.Text = Format(CStr(TextBox1.Text)) & Convert.ToInt32(str)
End If
i want in webservice..
You will find all your answers here http://www.asp.net/web-api

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?