Error showing while updating database with Identity Column - vb.net

Please help me... i am trying to update my database from VB.net. It shows error. My code is given below....
Try
getConnect()
Dim strSQL As String
strSQL = " UPDATE DEPARTMENT SET [DEP_ID]=#DEP_ID,[DEPART]=#DEPART, [DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
And the error is:
ERROR: Cannot update identity column 'DEP_ID'

Remove [DEP_ID]=#DEP_ID, from the SET. It makes no sense to try and set it to the value already ensured by the WHERE anyway so it is clearly redundant and it is not permitted to update IDENTITY columns.
UPDATE DEPARTMENT
SET [DEPART] = #DEPART,
[DEP_DSCRPTN] = #DEP_DSCRPTN
WHERE [DEP_ID] = #DEP_ID

The error message is clear, remove the Set DEP_ID = #DEP_ID part.
Try
getConnect()
Dim strSQL As String
strSQL = "UPDATE DEPARTMENT SET [DEPART]=#DEPART," +
"[DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
If you find yourself in need to change an Identity column then I think you need to analyze better your database schema.

Related

Delete button code sometimes working

How to debug the following code?
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If
I reformatted your code so it was more readable:
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If
The number one issue I see here is that we do not see what the value of the key is you're deleting on , nor the format of the data that's in the table to delete from. It's impossible to determine what exactly is wrong from this code.
My suggestion is to set a breakpoint on this line cmd.ExecuteNonQuery() and see what the value of TextBox1.Text is and make sure it is what you expect it to be, look for leading/trailing spaces or anything else that's unexpected.. Other than that there isn't much else to go on here in terms of context.

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..

VB.NET get related data while entering input in textbox

I have two textboxes, one is for the ProductName and the 2nd is for ProductPrice.
I am not able to get the txtProductPrice value from the database while entering the txtProductname. Please help me
Here is the code I am trying to execute...
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "SELECT price FROM products WHERE name = '" & txtPN.Text & "'"
dr = cmd.ExecuteReader
If dr.Read Then
'what will i do here???
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

vb.net Inserting data to access database

I have the following code to input data into my Access database, but I am getting the following error.
Query input must contain at least one table or query.
What am I doing wrong? Here is the section of code that they is mentioning the lines.
Private Sub EditAddButton_Click(sender As Object, e As EventArgs) Handles EditAddButton.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*******************;Jet OLEDB:Database Password=************;")
Dim insertsql As String
Try
insertsql = "INSERT INTO RepairOrders" & _
"(ROOtherInfo, ROJobType, ROJobTime, RODelPicDate, RONo)" & _
"VALUES (#other, #type, #time, #delpic, #jobno) WHERE ROJobNo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have replaced certain information with asterixs' to cover some sensitive information.
EDIT:
Now I am getting a syntax error :(
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*********************************;Jet OLEDB:Database Password=***********;")
Dim insertsql As String
Try
insertsql = "UPDATE RepairOrders SET ROOther = #other, SET RONo = #jobno, SET ROJobType = #type, SET ROJobTime = #time, SET RODelPicDate = #delpic WHERE RONo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
It looks like you have too many SET statements, and OleDb requires '?' for parameters, and you must take care about the amount of them, and the order they are specified. This is a bit cleaned up, take a look at OLEDB Parameterized Query for a more thorough example.
Try
insertsql = "UPDATE RepairOrders
SET ROOther = ?
, RONo = ?
, ROJobType = ?
, SET ROJobTime = ?
, SET RODelPicDate = ?
WHERE RONo = ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("?", AddOtherText.Text)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
cmd.Parameters.AddWithValue("?", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("?", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("?", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

SQL Update with where clause with variables from VS2010 Winforms

I am trying to do an update query from a winform with two variables without using a dataset.
I assign both of my variable and then run the query but it keeps giving the error that zcomp is not a valid column name. Which of course is true but I tell it which column before I say = zcomp. Below is my code that is running the query.
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - zamnt WHERE [ComponentID] = zcomp"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
I have tried it several different ways. It works just fine if I take out the zamnt and zcomp and put the actual number values that are in the variables. Please help I've been searching all day for a way to use the variables with this update query.
Thanks,
Stacy
You are probably looking for how to use parameters in ADO.NET. For your example, it can look like this:
cmd.Parameters.Add("#zamnt", zamnt);
cmd.Parameters.Add("#zcomp", zcomp);
Put these two lines anywhere before ExecuteNonQuery.
Because parameters need a # prefix, you would also need to change your query to say #zamnt instead of just zamnt, and same for zcomp:
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
In addition to using parameters, the "Using" statement closes the connection and disposes resources:
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Try
Using con As New SqlConnection("Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True")
con.Open()
Using cmd As New SqlCommand
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
cmd.Parameters.AddWithValue("#zamt", zamnt)
cmd.Parameters.AddWithValue("#zcomp", zcomp)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
have u tried this?
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] -" + zamnt + " WHERE [ComponentID] =" + zcomp
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try