How to avoid duplicate entries when saving in database in vb.net - sql-server

I have a button but it can save duplicate entries i don't know how to correctly put a if not exist operator pls help..
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
cn.Open()
i = cmd.ExecuteNonQuery
cn.Close()
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If

You can use NOT EXISTS to prevent duplicate insert:
Dim sql = "INSERT INTO Students(Familyname, Firstname, Middlename, StudentID) " & _
"VALUES(#FamilyName, #Firstname, #Middlename, #StudentID)" & _
"WHERE NOT EXISTS(SELECT 1 FROM Students WHERE StudentId = #StudentID)"
Using cn As New SqlConnection("Your connection string here")
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Parameters.Add("#FamilyName", SqlDbType.VarChar, 50).Value = txtname.Text
cmd.Parameters.Add("#Firstname", SqlDbType.VarChar, 50).Value = txtfname.Text
cmd.Parameters.Add("#Middlename", SqlDbType.VarChar, 50).Value = txtmname.Text
cmd.Parameters.Add("#StudentID", SqlDbType.VarChar, 50).Value = txtid.Text
Dim i = cmd.ExecuteNonQuery
End Using
You should always use parameterized queries to avoid SQL Injection attacks.
NOTE: Please apply appropriate field types.

Try this one :
cn.Open()
Dim intReturn as integer
Dim strSql as string = "Select * from Students where StudentID = #StudentID"
sqlcmd = new sqlcommand(strSql, cn)
With sqlcmd.parameters
.addwithvalue("#StudentID", ctype(txtid.text,string)
End with
intReturn = sqlcmd.ExecuteScalar
If(intReturn > 0)
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
i = cmd.ExecuteNonQuery
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If
Else
MsgBox("Student Already Exist", MessageBoxIcon.Error, "Error")
End If
cn.Close()
And don't forget to make your StudentID field as Unique in your database.

Related

vb.net creating table. using textbox.text for the per column of table

I have a program that add new employee it adds there personal information and there benefits id (ex. tax number). but i want to do is create a new table for there salary by making a new table and the columns will be there benefits id (ex.tax number) but i want to create the table automatically after the new employee is added here is my code if it will help you:
BTW IM GETTING A MESSAGEBOX THAT SHOW "incorrect syntax near '#idd'.
Dim add As String = String.Empty
add &= "insert into rec_member(firstname,middlename,lastname,age,birthday,pagibig,philhealth,sss,tin,department)"
add &= "values "
add &= "(#first,#middle,#last,#age,#bday,#pagibig,#philhealth,#sss,#tin,#dept);select scope_identity()"
Dim benefits As String = String.Empty
benefits &= "create table #idd(" & _
"pagibig(#ibig) integer not null, " & _
"philhealth(#phil) integer not null," & _
"sss(#rsss) integer not null," & _
"tin(#rtin) integer not null)"
Using conn As New SqlConnection("server=WIN10;database=add_member;user=hradmin;password=admin;")
Using cmd As New SqlCommand
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = add
.Parameters.Add("#first", SqlDbType.VarChar).Value = afirstname.Text
.Parameters.Add("#middle", SqlDbType.VarChar).Value = amiddlename.Text
.Parameters.Add("#last", SqlDbType.VarChar).Value = alastname.Text
.Parameters.Add("#age", SqlDbType.Int).Value = aage.Value
.Parameters.Add("#bday", SqlDbType.Date).Value = abirthday.Text
.Parameters.Add("#pagibig", SqlDbType.Int).Value = apagibig.Text
.Parameters.Add("#philhealth", SqlDbType.Int).Value = aphilhealth.Text
.Parameters.Add("#sss", SqlDbType.Int).Value = asss.Text
.Parameters.Add("#tin", SqlDbType.Int).Value = atin.Text
.Parameters.Add("#dept", SqlDbType.VarChar).Value = adepartment.SelectedItem
End With
Try
conn.Open()
If afirstname.Text.Length < 2 Then
MsgBox("Please input more value on the FIRST NAME")
ElseIf amiddlename.Text.Length < 2 Then
MsgBox("Please input more value on the MIDDLE NAME")
ElseIf alastname.Text.Length < 2 Then
MsgBox("Please input more value on the LAST NAME")
ElseIf aage.Value < 16 Then
MsgBox("Age must be appropriate")
ElseIf abirthday.Text > "1997-01-01" Then
MsgBox("Please select a birthday")
ElseIf apagibig.Text.Length < 5 Then
MsgBox("Please input more value on the PAG-IBIG")
ElseIf adepartment.SelectedItem = "" Then
MsgBox("Please Select a Department")
ElseIf aphilhealth.Text.Length < 5 Then
MsgBox("Please input more value on the PHILHEALTH")
ElseIf asss.Text.Length < 5 Then
MsgBox("Please input more value on th SSS")
ElseIf atin.Text.Length < 5 Then
MsgBox("Please input more value on the TIN")
Else
Dim id As Integer = CInt(cmd.ExecuteScalar)
MsgBox("NEW EMPLOYEE ADDED" & Environment.NewLine &
"ID NUMBER:" & id & Environment.NewLine &
"FIRST NAME:" & afirstname.Text & Environment.NewLine &
"MIDDLE NAME:" & amiddlename.Text & Environment.NewLine &
"LAST NAME:" & alastname.Text & Environment.NewLine &
"AGE:" & aage.Value & Environment.NewLine &
"BIRTHDAY:" & abirthday.Text & Environment.NewLine &
"PAG-IBIG:" & apagibig.Text & Environment.NewLine &
"PHIL-HEALTH:" & aphilhealth.Text & Environment.NewLine &
"SSS:" & asss.Text & Environment.NewLine &
"TIN:" & atin.Text & Environment.NewLine &
"DEPARTMENT:" & adepartment.SelectedItem & Environment.NewLine
)
Using cmd1 As New SqlCommand
With cmd1
.Connection = conn
.CommandType = CommandType.Text
.CommandText = benefits
.Parameters.Add("#idd", SqlDbType.Int).Value = id
.Parameters.Add("#ibig", SqlDbType.Int).Value = apagibig.Text
.Parameters.Add("#phil", SqlDbType.Int).Value = aphilhealth.Text
.Parameters.Add("#rsss", SqlDbType.Int).Value = asss.Text
.Parameters.Add("#rtin", SqlDbType.Int).Value = atin.Text
End With
cmd1.ExecuteNonQuery()
MsgBox("New Table is Set for new employee")
End Using
End If
afirstname.Clear()
amiddlename.Clear()
alastname.Clear()
aage.Value = 0
abirthday.Text = "1997-01-01"
apagibig.Clear()
adepartment.ResetText()
aphilhealth.Clear()
asss.Clear()
atin.Clear()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
The problem is:
create table #idd ...
you cant send command with non static table-name.
for this, you need build the command-text with tokens:
benefits &= "create table {0}(" & _
"pagibig(#ibig) integer not null, " & _
"philhealth(#phil) integer not null," & _
"sss(#rsss) integer not null," & _
"tin(#rtin) integer not null)"
and:
Using cmd1 As New SqlCommand
With cmd1
.Connection = conn
.CommandType = CommandType.Text
.CommandText = String.Format(benefits, id)
.Parameters.Add("#ibig", SqlDbType.Int).Value = apagibig.Text
.Parameters.Add("#phil", SqlDbType.Int).Value = aphilhealth.Text
.Parameters.Add("#rsss", SqlDbType.Int).Value = asss.Text
.Parameters.Add("#rtin", SqlDbType.Int).Value = atin.Text

update button codes for VB.net with sql-server

I have create a library management system. here if I want to update a book's particular record its updating all the records in the SQL-server database. how can I write code for update a particular record only. here is my code,
Private Sub btnedit_Click(sender As Object, e As EventArgs) Handles btnedit.Click
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Add a WHERE clause in your SQL command to specify which book will be updated..
use the ID number of the book you want to update.
and avoid concatenating in your sql command, use parameter #
Dim comd As New SqlCommand("update Book set Book_Id=#bookID, Bk_Name=#bkName, Author_Name=#author, Year_of_release=#release, Availability_of_bks=#avail WHERE Book_Id=#whereID", con)
comd.Parameters.Add("#bookID", SqlDbType.String).Value = TextBox1.Text
comd.Parameters.Add("#bkName", SqlDbType.String).Value = TextBox2.Text
comd.Parameters.Add("#author", SqlDbType.String).Value = TextBox3.Text
comd.Parameters.Add("#release", SqlDbType.String).Value = TextBox4.Text
comd.Parameters.Add("#avail", SqlDbType.String).Value = TextBox5.Text
comd.Parameters.Add("#whereID", SqlDbType.String).Value = "Book ID HERE"
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
You need to add a WHERE clause to your SqlCommand so that SQL Server knows what record to update. Without a WHERE clause, it will update the entire table. See below:
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "' WHERE Book_Id='{**Put your book id here**}'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Additional information: Syntax error in INSERT INTO statement

I tried out to connect my database(ms-access) to Visual basic.But it came up with the following error:
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
I used the following code.please see if there is any error..please help me out for it..
The Code is:
Private Sub frmGive_Load(sender As Object, e As EventArgs) Handles Me.Load
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
Dim sql As String = "Select * from tblGive"
Dim dbcmd As OleDbCommand = New OleDbCommand(sql, con)
con.Open()
Dim dbadapter As OleDbDataAdapter = New OleDbDataAdapter(sql, con)
Dim db As DataSet = New DataSet("TABLE")
dbadapter.Fill(db, "TABLE")
'create new instance of table so that row can be accessed
Dim dt As New DataTable
dt = db.Tables("TABLE")
CmbGenre.Text = dt.Rows(0)(0)
CmbLanguage.Text = dt.Rows(0)(1)
txtNMovie.Text = dt.Rows(0)(2)
txtFName.Text = dt.Rows(0)(3)
txtLname.Text = dt.Rows(0)(4)
CmbClass.Text = dt.Rows(0)(5)
txtnull.Text = dt.Rows(0)(6)
End Sub
There are some codes in between them.Including textboxes and combo boxes.
Public Sub submit()
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
con.Open()
Dim sql As String
sql = "Insert into tblGive (Genre,Language,NMovie,FName,LName,Class,SaveDate)" + "VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text & "','" & txtNMovie.Text & "','" & txtFName.Text & "','" & txtLname.Text & "','" & CmbClass.Text & "','" & txtnull.Text & "')"
MsgBox(sql)
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand(sql, con)
dbcmd.ExecuteNonQuery()
MsgBox("Saved")
End Sub
You are missing a single quote at the beginning of the values keyword.
In other words,
VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text &
should be
VALUES ('" & CmbGenre.Text & "','" & CmbLanguage.Text &

sql Transaction and dual table insertion in vb.net

What I wanted to do is insert data on the first table, then get the last inserted ID on the first table and insert it on the second. I already got this without transaction, but I can't do it because I need to have transactions later on because I will add a lot of inserts in one go.
This is my code so far..
Take note that this is inside a transaction..
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)"
command.Parameters.Add("#myCarID", SqlDbType.Int).Value = pCarID
command.Parameters.Add("#myDate", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myMechanic", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myOverseer", SqlDbType.VarChar).Value = pOverseer
command.Parameters.Add("#myDescription", SqlDbType.VarChar).Value = pDescription
command.Parameters.Add("#myDateNext", SqlDbType.DateTime).Value = pNext
command.Parameters.Add("#myAmount", SqlDbType.Float).Value = pAmount
command.ExecuteNonQuery()
'insert records on the second table (the problem is here)
command.CommandText = "INSERT INTO tblCarMaintenance2 " & _
"(ID_Main, ID_Supplier, fParts, fAmount) " & _
"VALUES (#myMainID, #mySupplierID, #myParts, #myAmount) " & _
"FROM tblCarMaintenance"
command.Parameters.Add("#myMainID", SqlDbType.Int).Value = myID
command.Parameters.Add("#mySupplierID", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myParts", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myAmount", SqlDbType.VarChar).Value = pOverseer
command.ExecuteNonQuery()
transaction.Commit()
EDIT: #myMainID is the parameter equal to the last inserted ID on tblCarMaintenance
EDIT:
The solution for the problem is this:
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)" & _
"Select SCOPE_IDENTITY()"
command.Parameters.Add("#myCarID", SqlDbType.Int).Value = pCarID
command.Parameters.Add("#myDate", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myMechanic", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myOverseer", SqlDbType.VarChar).Value = pOverseer
command.Parameters.Add("#myDescription", SqlDbType.VarChar).Value = pDescription
command.Parameters.Add("#myDateNext", SqlDbType.DateTime).Value = pNext
command.Parameters.Add("#myAmount", SqlDbType.Float).Value = pAmount
Dim InsertedItemID = command.ExecuteScalar()
command.CommandText = "INSERT INTO tblCarMaintenance2 " & _
"(ID_Main, ID_Supplier, fParts, fAmount) " & _
"VALUES (" & InsertedItemID & ", #mySupplierID, #myParts, #myAmount2) "
command.Parameters.Add("#mySupplierID", SqlDbType.Int).Value = pSupplier
command.Parameters.Add("#myParts", SqlDbType.VarChar).Value = pParts
command.Parameters.Add("#myAmount2", SqlDbType.Float).Value = 12
command.ExecuteNonQuery()
In your first query, edit to:
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)" & _
"Select SCOPE_IDENTITY()";
and change the first command.ExecuteNonQuery() to:
Dim InsertedItemID = command.ExecuteScalar()

Visual Basic .NET Access Database Record Add

I have problem with database save changes:
coon1.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & _
"magazyn.mdb"
sql = "INSERT INTO magazyn (ID_Towaru,Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) VALUES ('" & jakiid & "','" & kodtowaru & "','" & nazwatowaru & "','" & iloscwmagazynie & "','" & iloscminimalna & "',0)"
Dim MyConnection As New OleDbConnection(conn)
Dim command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.ExecuteNonQuery()
MyConnection.Close()
I try add new record to table magazyn, but when opened database with Access then I didn't see any new record related to magazyn in the table. But ViewGrid shows me this new element until I close and re-open the program.
Does someone know where the problem is?
Always use parameters and not string concatenation. This rule should be followed categorically
sql = "INSERT INTO magazyn " +
"(Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) " +
"VALUES (?, ?, ?, ?,0)"
Using MyConnection As New OleDbConnection(conn)
Using command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.Parameters.AddWithValue("#Kod", kodtowaru)
command1.Parameters.AddWithValue("#naz", nazwatowaru)
command1.Parameters.AddWithValue("#ilo", iloscwmagazynie)
command1.Parameters.AddWithValue("#mini", iloscminimalna)
command1.ExecuteNonQuery()
End Using
End Using
This, of course, requires that the variables used as value for the parameters are of the correct datatype.
Please Insert This Below Coding in Module.
Imports System.Data.OleDb
Module Module1
Public OleCn As New OleDbConnection()
Public Function StrConnection() As String
StrConnection = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Testing.Accdb;"
Return StrConnection
End Function
After This Insert the Below Coding in Save Button.
Dim msg As DialogResult = MessageBox.Show("Do you want to Save this Record? ", "Response", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (msg = vbYes) Then
If RequiredEntry() = True Then
Return
End If
Try
With OleCn
If .State <> ConnectionState.Open Then
.ConnectionString = StrConnection()
.Open()
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Try
Dim sSQL As String = "insert into Vendor values(#VendorCode,#VendorName,#Address,#City,#LandPhone,#Mobile,#EmailID,#Balance)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, OleCn)
'VendorCode
Dim VendorCode As OleDbParameter = New OleDbParameter("#VendorCode", OleDbType.VarChar, 10)
VendorCode.Value = txtVendorCode.Text.ToString()
cmd.Parameters.Add(VendorCode)
'VendorName
Dim VendorName As OleDbParameter = New OleDbParameter("#VendorName", OleDbType.VarChar, 25)
VendorName.Value = txtVendorName.Text.ToString()
cmd.Parameters.Add(VendorName)
'Address
Dim Address As OleDbParameter = New OleDbParameter("#Address", OleDbType.VarChar, 50)
Address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(Address)
'City
Dim City As OleDbParameter = New OleDbParameter("#City", OleDbType.VarChar, 25)
City.Value = txtCity.Text.ToString()
cmd.Parameters.Add(City)
'LandPhone
Dim LandPhone As OleDbParameter = New OleDbParameter("#LandPhone", OleDbType.VarChar, 50)
LandPhone.Value = txtLandPhone.Text.ToString()
cmd.Parameters.Add(LandPhone)
'Mobile
Dim Mobile As OleDbParameter = New OleDbParameter("#Mobile", OleDbType.VarChar, 15)
Mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(Mobile)
'EmailID
Dim EmailID As OleDbParameter = New OleDbParameter("#EmailID", OleDbType.VarWChar, 25)
EmailID.Value = txtEmailID.Text.ToString()
cmd.Parameters.Add(EmailID)
'Balance
Dim Balance As OleDbParameter = New OleDbParameter("#Balance", OleDbType.VarWChar, 10)
Balance.Value = txtBalance.Text.ToString()
cmd.Parameters.Add(Balance)
If cmd.ExecuteNonQuery() Then
OleCn.Close()
MessageBox.Show("New Record is Added Successfully.", "Record Saved")
Call clear()
Else
MsgBox("Record Addition Failed ", MsgBoxStyle.Critical, "Addition Failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
End If

Resources