How to check for duplicate value in database when importing vb.net - vb.net

For i As Integer = 0 To dgclassinfo.Rows.Count - 1
LRN = dgclassinfo.Rows(i).Cells(2).Value.ToString
Lname = dgclassinfo.Rows(i).Cells(3).Value.ToString
Fname = dgclassinfo.Rows(i).Cells(4).Value.ToString
Mname = dgclassinfo.Rows(i).Cells(5).Value.ToString
comm.CommandText = "insert into g7(LRN,Lname,Fname,Mname ) values('" & LRN & "','" & Lname & "','" & Fname & "','" & Mname & "')"
comm.ExecuteNonQuery()
Next
I used to code above to import my data. Using dgv. My data is databound. for additional info. When I import the file it reads the value of the excel and displays in the dgv in which i insert the data using the for loop above. I think I need to use mydr.hasrows but I have no idea on how to do this using for loop. How can I check for duplicate records every row? LRN is my pk.
Any help will be appreciated.

To check if record exists, u can actually check the database's specific column to see if the column has any rows containing the same record u are trying to insert..TO do this,first u need to check the database for duplicates and then insert new data if no duplicates exist.A full example might look like this :
Dim cmd as new SqlCommand("Select * from TABLENAME([column names-remove brackets if required])values(#value1)",con)
cmd.parametres.AddWithValue("#value1",Firstname.Text)
Dim dr as new SqlDataReader=cmd.Executereader
If dr.hasRows Then 'This checks if any duplicates exist
Msgbox("Duplicates Found")
Else
Dim cmd as new SqlCommand("Inserting data query here",con)
cmd.parametres.Add("#value1",SqlDbtype.Varchar).value=Firstame.Text
cmd.ExecuteNonQuery
Here i've assumed u r using Sql Server, make necessary changes to the code

Related

Problem importing an excel workbook into Access and adding a column; error 3127

I am creating a form in an Access database that allows a user to import an Excel workbook into the database, then inserts a column with that day's date as a way to log when the record was imported, with the idea that I can later compare this to a master database and update accordingly.
My code is below:
Private Sub btnImport_Click()
'create a new file system object that will check for conditions and import the file as a new table if a valid name is chosen
Dim FSO As New FileSystemObject
Dim strSQL As String
'Dim curDatabase As Object
Dim tableTest As Object
Dim fieldNew As Object
Dim todayDate As Date
Dim tempTable As String
tempTable = "TempTable" & CStr(Date)
'MsgBox TempTable
'If no file name in box
If Nz(Me.txtFileName, "") = "" Then
MsgBox "Please choose a file."
Exit Sub
End If
'If a file name is in box and the file can be located
If FSO.FileExists(Me.txtFileName) Then
fileImport.ImportExcel Me.txtFileName, tempTable
'once it imports the table, it then adds today's date (the upload date)
todayDate = Date
strSQL = "INSERT INTO tempTable (Upload_Date) Values (#" & Date & "#);"
DoCmd.RunSQL strSQL
'DoCmd.RunSQL ("DROP Table TempTable")
Else
'Error message if file can't be found
MsgBox "File not found."
End If
End Sub
Unfortunately, right now I am getting two problems.
The first is
run-time error 3127: The INSERT INTO statement contains an unknown
field name.
I thought I wanted to insert a new field, so I'm a little perplexed by this error.
I'm also getting another error; the compiler doesn't seem to like when I use tempTable for the table name. I'm trying to use a reference to the table name, rather than the actual name of the table itself, because this will end up being a daily upload, so the name of the table that is having this column inserted into it will change every day.
I appreciate any guidance that you can give; I'm fairly new to VBA.
UPDATE: I ended up solving this issue by A. using an UPDATE statement and using CurrentDb.Execute to add the date. I found that this worked for me:
strSQL = "ALTER TABLE TempTable ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE TempTable SET Upload_Date = '" & Date & "'"
DoCmd.RunSQL strSQL
CurrentDb.Execute strSQL2
INSERT INTO doesn't add columns, it just adds rows (with data in existing columns). Look into ALTER TABLE ( https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql )
I'm not sure if it's related, but the table name you use in strSQL is "tempTable", yet the table name you pass to fileImport.ImportExcel is "TempTable" (i.e. the capitalization of the first letter is inconsistent).
If the variable "tempTable" is meant to hold the name of the table (so it can be used for different table names) then it should be outside of the SQL strings:
strSQL= "ALTER TABLE " & tempTable " & " ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE " & tempTable & " SET Upload_Date = '" & Date & "';"
Otherwise you are amending and updating a table called "TempTable" rather than inserting the calculated table name from the variable into the SQL string.
Also note that there should be a semi-colon at the end of strSQL2 as well.

How do I access multiple records from the same table using SQLDataAdapter?

This almost works. I get an error at the last line that looks like it's complaining about the C1 reference. Is there a simple way around this? There is nothing wrong with the query or connection.
Dim CmdString As String
Dim con As New SqlConnection
Try
con.ConnectionString = PubConn
CmdString = "select * from " & PubDB & ".dbo.Suppliers as S " & _
" join " & PubDB & ".dbo.Address as A" & _
" on S.Supplier_Address_Code = A.Address_IDX" & _
" join " & PubDB & ".dbo.Contacts as C1" & _
" on S.Supplier_Contact1 = C1.Contact_IDX" &
" join " & PubDB & ".dbo.Contacts as C2" & _
" on S.Supplier_Contact2 = C2.Contact_IDX" &
" WHERE S.Supplier_IDX = " & LookupIDX
Dim cmd As New SqlCommand(CmdString)
cmd.Connection = con
con.Open()
Dim DAdapt As New SqlClient.SqlDataAdapter(cmd)
Dim Dset As New DataSet
DAdapt.Fill(Dset)
con.Close()
With Dset.Tables(0).Rows(0)
txtAddress1.Text = .Item("Address1").ToString
txtAddress2.Text = .Item("Address2").ToString
txtSupplierName.Text = .Item("Address_Title").ToString
txtAttn.Text = .Item("Attn").ToString
txtBusinessPhone1.Text = .Item("C1.Contact_Business_Phone").ToString
You would not include the "C1" table alias as part of your column name. It will be returned from your query as Contact_Business_Phone.
For accessing multiple rows you could use the indexer as you are in the example above "Rows(0)" by placing your With block into a For loop and accessing the "Rows(i)" with your loop variable. However, this would not help much as your are assigning this to individual text boxes, so you'd only see the last value on your page/screen.
The alias C1 is used by SQL Server and is not persisted to the result set. Have you taken this query into SQL Management Studio to see the results?
Since you requested all columns (*) and joined to the Contacts table twice, you'll end up with duplicate column names in the result. For example, if the Contacts table has a LastName field, you'll end up with TWO LastName columns in your result.
I haven't tried to duplicate this in my local environment, but I can't imagine the data adapter is going to like having duplicate column names.
I recommend specifically including the columns you want to return instead of using the *. That's where you'll use the alias of C1, then you can rename the duplicate columns using the AS keyword:
SELECT C1.LastName AS [Supplier1_LastName],
C2.LastName AS [Supplier2_LastName],
...
This should solve your problem.
Good Luck!
You should only be pulling back the columns that you're in fact interested in, as opposed to *. It's sort of hard to tell exactly what data exists in which tables since you're pulling the full set, but at a quick guess, you'll want in your select statement to pull back A.Address1, A.Address2, A.AddressTitle, ?.Attn (not sure which table this actually derives from) and C1.Contact_Business_Phone. Unless you actually NEED the other fields, you're much better off specifying the individual fields in your query, besides having the possible duplicate field issue that you're running into here, it can also be a significant performance hit pulling everything in. After you clean up the query and only pull in the results you want, you can safely just reference them the way you are for the other fields, without needing a table alias (which as others have pointed out, isn't persisted to the result set anyways).

How to check the exist value

Using VB.Net and Sql Server
I want to check the user Entry Value.
The User is entering the code in the textbox, before saving to the table, i want to check whethere code is already exist in the table or not.
Tried Code
cmd = New SqlCommand("Select code from table where code = '" & textbox1.Text & "' ", Con)
dr = cmd.ExecuteReader()
While dr.Read()
End While
If value is exist, then message to the user "Already Exist" other wise save to the table.
Need Vb.net Code Help
Use SELECT COUNT instead and then check for that being greater than zero:
cmd = New SqlCommand("SELECT COUNT(*) from table where code = '" & textbox1.Text & "' ", con)
Dim NumRecords as Int32 = cmd.ExecuteScalar
IF NumRecords > 0 THEN...
Make code as primary key since you want it to be unique
if the value entered by the user in code is already existing in the table , VIOLATION of primary key sql exception will be thrown
Catch that exception and display a warning message!

vb.net MS Access inserting rows from one db to another

I'm trying to import rows from one db to another, basically it something to do with this SQL:
SELECT * INTO [MSAccess;DATABASE=C:\MainDB.mdb;].[Header] FROM [Header] WHERE ID=9
As it returns this error: Could not find installable ISAM.
Any ideas? To help explain I've added my code:
Dim sSQL As String
Dim iCertMainNo As Integer
Dim cnLocal As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & App_Path() & "LocalDB.mdb;")
Dim cnMain As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & My.Settings.MainDB & ";")
cnLocal.Open()
cnMain.Open()
Dim cmd As New System.Data.OleDb.OleDbCommand("SELECT * INTO [MSAccess;DATABASE=" & My.Settings.MainDB & ";].[tblCertHeader] FROM tblCertHeader WHERE ID = " & iCertNo, cnLocal)
cmd.ExecuteNonQuery()
cnMain.Close()
cnLocal.Close()
I'm thinking it's either do it the way listed above. Or to open two connections get one row from the local and then insert it into cnMain - but again not sure how to do this without listing all the fields... Can I just simply insert the row ?
it appears you are running from one MS Access database to another, so the connect string is much simpler:
SELECT * INTO [;DATABASE=C:\MainDB.mdb;].[Header] FROM [Header] WHERE ID=9
BTW It may not be possible to update a database in C:\, if that is a real path.
EDIT I tested with this:
''Dim sSQL As String
''Dim iCertMainNo As Integer
Dim cnLocal As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Docs\dbFrom.mdb;")
''Dim cnMain As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & My.Settings.MainDB & ";")
cnLocal.Open()
''cnMain.Open()
Dim cmd As New System.Data.OleDb.OleDbCommand("SELECT * INTO [;DATABASE=C:\Docs\DBTo.mdb;].[Header] FROM Header WHERE ID = 2", cnLocal)
cmd.ExecuteNonQuery()
''cnMain.Close()
cnLocal.Close()
And it worked fine for me. I commented out iCertMainNo because you did not use it. Your string included only iCertNo, for which i used the actual value for test purposes. I did not see any reason for two connections.

how to check whether the table is empty

hie all,
i want to insert the data into the table only if the table is empty, so for that i need to check the condition to check whether data already exists in the table, if present then i want to empty the table before inserting the the fresh value.
i know how to insert and delete the data only prob is to check the condition. so please can any help me out in this.
TO INSERT
Dim comUserSelect As OleDbCommand
myDateTime(i) = DateTime.Parse(arr_dateTime(i))
' Console.WriteLine(r("P1"))
Dim strSELEsCTa As Integer = r("P1")
If ins < 10 Then
ins = ins + 1
Dim strSELECTa As String = "insert into tblvalues (DataTime ,P1) values ('" & DateTime.Parse(arr_dateTime(i)) & "','" & strSELEsCTa & "')"
Dim dadte_s As New OleDbDataAdapter(strSELECTa, conn)
comUserSelect = New OleDbCommand(strSELECTa, conn)
comUserSelect.ExecuteNonQuery()
End If
*TO DELETE *
Dim strDelete As String = "delete * from tblvalues "
now i don know how to check the condition
"SELECT COUNT(*) FROM your_table_name"
If the table is empty, this should return 0.
Alternatively, you could try to select a row from the table and based on the response act upon it.
"SELECT * FROM your_table_name LIMIT 0, 1"