get last inserted primary key record in database - vb.net

Please help to get the primary key of the last insert record as the one which i have gives me duplicate rows in the database and return 0
Try
If Conn.State = ConnectionState.Open Then Conn.Close()
'insert the new customer data
Conn.Open()
cmd = New SqlCommand("insert into Quote values ('" & dateOFCreat & "','" & Emp & "','" & Customer_no & "' )", Conn)
Dim a As Integer = cmd.ExecuteNonQuery()
Dim results As Integer
Dim cmd_results As SqlCommand
'Get the last created Quote in the Database
cmd_results = New SqlCommand("Select ##Identity from Quote", Conn)
results = cmd.ExecuteScalar
TxtLastQuoteID.Text = results
If a = 0 Then
MsgBox("Error")
End If
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

You can make use of the batch commands supported by Sql Server. Just put together the two instructions and just use ExecuteScalar. However, before that, you need to fix ASAP your Sql Injection vulnerability. Do not concatenate strings to build an sql command, but use parameters.
Try
Using con as SqlConnection = new SqlConnection(....constringhere...)
Conn.Open()
Dim sqlText = "insert into Quote values (#dat,#emp,#cusno); SELECT SCOPE_IDENTITY()"
cmd = New SqlCommand(sqlText,Conn)
cmd.Parameters.Add("#dat", SqlDbType.NVarChar).Value = dateOFCreat
cmd.Parameters.Add("#end", SqlDbType.NVarChar).Value = emp
cmd.Parameters.Add("#cusno", SqlDbType.NVarChar).Value = Customer_no
Dim lastID As Integer = cmd.ExecuteScalar()
TxtLastQuoteID.Text = lastID.ToString()
Conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Notice also that is a very bad thing to keep a global connection object. You don't need that because ADO.NET implements Connection Pooling that makes opening a connection a very fast operation. Instead keeping a connection around requires a lot of effort to work correctly around it
Finally you can look here to better understand the difference between SCOPE_IDENTITY and ##IDENTITY and why is usually better to use the first one.

Related

Insert text into MS access cells

i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Why Cant i delete rows in a table

I cant delete rows in a table
it doesn't come up with any error messages
con has been used on other statements and works just fine
textbox1 is read-only and gets input from a listbox filled with the values of the "Driver" column
and check() is just to refresh the listbox containing the values
con.Open()
Try
success = True
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver='" & TextBox1.Text & "';", con)
Catch ex As Exception
MsgBox(ex.Message)
success = False
End Try
If success Then
MsgBox("Success")
End If
con.Close()
check()
You never execute the command. Add a call to SqlCommand::ExecuteNonQuery
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver='" & TextBox1.Text & "';", con)
cmd.ExecuteNonQuery() ' added
That said you should not use string concatenation when adding values to your sql statement. Instead use Parameters which prevents sql injection attacks.
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver= #driver", con)
cmd.Parameters.Add("#driver", SqlDbType.VarChar).Value = TextBox1.Text ' add parameter
cmd.ExecuteNonQuery() ' added
Assumption
Driver is a column inside a table with the same name Driver. If this is not the case then you do not understand tables and columns or the DELETE statement which in its basic form is DELETE FROM [TABLE] WHERE [condition on one or more columns]

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

How do I assign the results of an SQL query to multiple variables in VB.NET?

This is my first attempt at writing a program that accesses a database from scratch, rather than simply modifying my company's existing programs. It's also my first time using VB.Net 2010, as our other programs are written in VB6 and VB.NET 2003. We're using SQL Server 2000 but should be upgrading to 2008 soon, if that's relevant.
I can successfully connect to the database and pull data via query and assign, for instance, the results to a combobox, such as here:
Private Sub PopulateCustomers()
Dim conn As New SqlConnection()
Dim SQLQuery As New SqlCommand
Dim daCustomers As New SqlDataAdapter
Dim dsCustomers As New DataSet
conn = GetConnect()
Try
SQLQuery = conn.CreateCommand
SQLQuery.CommandText = "SELECT Customer_Name, Customer_ID FROM Customer_Information ORDER BY Customer_Name"
daCustomers.SelectCommand = SQLQuery
daCustomers.Fill(dsCustomers, "Customer_Information")
With cboCustomer
.DataSource = dsCustomers.Tables("Customer_Information")
.DisplayMember = "Customer_Name"
.ValueMember = "Customer_ID"
.SelectedIndex = -1
End With
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
conn.Close()
End Sub
I also have no problem executing a query that pulls a single field and assigns it to a variable using ExecuteScalar. What I haven't managed to figure out how to do (and can't seem to hit upon the right combination of search terms to find it elsewhere) is how to execute a query that will return a single row and then set various fields within that row to individual variables.
In case it's relevant, here is the GetConnect function referenced in the above code:
Public Function GetConnect()
conn = New SqlConnection("Data Source=<SERVERNAME>;Initial Catalog=<DBNAME>;User Id=" & Username & ";Password=" & Password & ";")
Return conn
End Function
How do I execute a query so as to assign each field of the returned row to individual variables?
You probably want to take a look at the SqlDataReader:
Using con As SqlConnection = GetConnect()
con.Open()
Using cmd As New SqlCommand("Stored Procedure Name", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#param", SqlDbType.Int)
cmd.Parameters("#param").Value = id
' Use result to build up collection
Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleResult Or CommandBehavior.SingleRow)
If (dr.Read()) Then
' dr then has indexed columns for each column returned for the row
End If
End Using
End Using
End Using
Like #Roland Shaw, I'd go down the datareader route but an other way.
would be to loop through
dsCustomers.Tables("Customer_Information").Rows
Don't forget to check to see if there are any rows in there.
Google VB.Net and DataRow for more info.

How to delete the contents of a related record from two tables?

The StudentDetails.Students is the master table which forms a relationship with RegistrationDetails.Registration. Therefore, StudentID is the primary key in the former whereas it is a foreign key in the latter.
Now I've tried each of the following codes but each of the first two gives an error message "Incorrect syntax near 'a'" and in the case of the third one DbTransaction as in "Dim trans As DbTransaction" is also not a valid type. Please I'm using SQL Server 2008 Professional Edition.
1.
cmd = New SqlCommand("DELETE FROM StudentDetails.Students a, RegistrationDetails.Registration b WHERE (b.StudentId=a.StudentId) AND a.StudentId='" & txtStudentID.Text & "'", cn)
2.
cmd = New SqlCommand("DELETE FROM StudentDetails.Students a, RegistrationDetails.Registration b WHERE (b.StudentId=a.StudentId) AND a.StudentId='/" & txtStudentID.Text & "/'", cn)
Don't specify the fields when deleting, delete from 1 table at a time, and wrap everything in a transaction:
Dim trans As SqlTransaction
trans = cn.BeginTransaction
Try
Dim cmd1 As New SqlCommand("Delete from Registration where StudentId='" & txtStudentID.Text & "'", cn)
cmd1.ExecuteNonQuery()
Dim cmd2 As New SqlCommand("Delete from StudentDetails where StudentId='" & txtStudentID.Text & "'", cn)
cmd2.ExecuteNonQuery()
trans.Commit()
Catch theException As Exception
' Report the exception
trans.Rollback()
End Try
I really don't know anything related to .NET, but you should try something like:
cmd = New SqlCommand("Delete from StudentDetails.Students a, RegistrationDetails.Registration b where (b.StudentId=a.StudentId) and a.StudentId='" & txtStudentID.Text & "'", cn)
Because you delete whole records, not columns, that is why you don't and can't specify column names in the DELETE clause
First delete all the records in "Registration" table related to specified StudentId.
Then, delete it from master table "StudentDetails".
and for keeping consistency of your data, use transaction.
Usually it's better to use transaction especially when deleting related data from two tables. Use parametrisation instead of concatenation and read more about SQL injection.
Your code should look more like this:
Using c As New SqlConnection("connection string")
c.Open()
Using tx As SqlTransaction = c.BeginTransaction()
Try
Using cmd As SqlCommand = c.CreateCommand()
cmd.CommandText = "delete from RegistrationDetails.Registration where StudentId = #studentId"
cmd.Parameters.Add("#studentId", SqlDbType.VarChar).Value = txtStudentID.Text
cmd.ExecuteNonQuery()
cmd.CommandText = "delete from StudentDetails.Students where StudentId = #studentId"
cmd.Parameters.Add("#studentId", SqlDbType.VarChar).Value = txtStudentID.Text
cmd.ExecuteNonQuery()
tx.Commit()
End Using
Catch generatedExceptionName As Exception
tx.Rollback()
' take care of exception here
Throw
End Try
End Using
End Using
I assume that StudentId column is varchar type (because of using apostrophes in: a.StudentId='" & txtStudentID.Text & "'"), if it's not change the SqlDbType.VarChar to whatever it is.