VB.net sql table not showing last rows - sql

What I am doing-
Importing 406 rows into 5 sql tables from excel sheet.
After import, I am manually saving data one by one into each of the 5
tables on button click event and displaying on datagridview..
After saving each record, I am refreshing datagridview.
My problem -
Records are getting saved properly, but datagridview shows only
408 records, where actual no. of records are 412.
When viewed from server explorer also, only 408 records are
shown.
But table properties show that there are 412 rows.
This problem is with only first table.
my code:-
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into pd([Adm No],[DOA],[Name],[Course],[Fees Due],[Concession],[Contact No 1]," & _
"[Contact No 2],[E-Mail],[Year of Passing],[Address],[DOB],[College])" & _
" values(#admno,#doa,#name,#course,#totalfees,#concession,#contactno1,#contactno2,#email,#yop," & _
"#address,#dob,#college)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#doa", date_format.format_date(doa.Value.Date))
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#totalfees", txt_totalfees.Text)
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#contactno1", txt_contact1.Text)
cmd.Parameters.AddWithValue("#contactno2", txt_contact2.Text)
cmd.Parameters.AddWithValue("#email", txt_email.Text)
cmd.Parameters.AddWithValue("#yop", txt_yop.Text)
cmd.Parameters.AddWithValue("#address", txt_address.Text)
cmd.Parameters.AddWithValue("#dob", date_format.format_date(dob.Value.Date))
cmd.Parameters.AddWithValue("#college", txt_college.Text)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save fees details
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into fees([Adm No],[Name],[Fees Due],[Fees Paid],[No of Installments]," & _
"[Installment Amounts],[Receipt Nos],[Dates of Transaction],[Mode],[Bank],[Due Date]" & _
",[Total Fees],[Concession],[Cheque No],[Course])" & _
" values(#admno,#name,#feesdue,#feespaid,#noi,#instamnt,#rcno,#dot,#mode,#bank,#dd," & _
"#total,#concession,#chqno,#course)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#feesdue", (CInt(txt_totalfees.Text) - CInt(txt_concession.Text)))
cmd.Parameters.AddWithValue("#feespaid", CInt(0))
cmd.Parameters.AddWithValue("#noi", CInt(0))
cmd.Parameters.AddWithValue("#instamnt", "")
cmd.Parameters.AddWithValue("#rcno", "")
cmd.Parameters.AddWithValue("#dot", "")
cmd.Parameters.AddWithValue("#mode", "")
cmd.Parameters.AddWithValue("#bank", "")
cmd.Parameters.AddWithValue("#dd", "")
cmd.Parameters.AddWithValue("#total", CInt(txt_totalfees.Text))
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#chqno", "")
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save photo
If Not PictureBox1.Image Is Nothing Then
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
Else
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
End If
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into attend values(#adm,#name,#course,#dt,#stat)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#dt", "")
cmd.Parameters.AddWithValue("#stat", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into testdb values(#adm,#name,#course,#tname,#tdate,#marksob,#marksout)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#tname", "")
cmd.Parameters.AddWithValue("#tdate", "")
cmd.Parameters.AddWithValue("#marksob", "")
cmd.Parameters.AddWithValue("#marksout", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()

problem was in the code of importing records. I was reading cells of excel file and inserting them into five tables.
Problem arises only if I import records in all five tables one by one, but if I import records into only three tables then the problem doesn't arise.
This solved my problem, but I didn't happen to know the actual reason behind it. Why can't I import records into five tables one after another? If anyone finds the reason behind the error please comment.

Related

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

VB.NET:Updating record in Ms Access

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

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!

VB.net 2010 dataset updates but access database remains same

I have tried to insert or update from my vb.net form into MS-Access database.
The dataset updates but the access database wont. Below is my code.
Try
Dim addLocation As String = "Insert into Provider (StateCode, Provider)" _
& "values ('" & ComboBox1.Text & "', '" & TextBox2.Text & "')"
Dim sqlcommand As New OleDbCommand
conn.Open()
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record added", MsgBoxStyle.Information)
refreshGrid()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Private Sub refreshGrid()
cnString = "PROVIDER = Microsoft.ace.oledb.12.0;data source =" & Application.StartupPath & "\HCHPClosedIn.accdb"
sqlQRY = "SELECT * FROM Provider"
conn = New OleDbConnection(cnString)
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Customers")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers"
End Try
End Sub
Its been a while but I think I recall Access is kinda picky with commit. Try this:
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
.transaction = trans
End With
Trans.Commit()