Data duplicates using Do While Loop in VB.NET - sql-server

I just wanted to ask why my data duplicates and how can I prevent it?
NOTE: my SQL query are working properly, the only problem is that every data it saves are duplicated based on the last value of ctr
Here is my code:
For Each lvi As ListViewItem In lvReportFormat2.Items
Dim count = lvReportFormat2.Items.Count
Dim ctr = 0
Dim orderby = 0
label.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Do While ctr < count
Label1.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Execute("INSERT INTO tblrptChad (accountcode,accountdesc,Type,class,Orderby,ReportType,Formula,Show)VALUES ('" & IIf(lvReportFormat2.Items(ctr).SubItems(0).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(0).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(1).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(1).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(2).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(2).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(3).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(3).Text, "NULL") & "','" & orderby & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(5).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(5).Text), 0)) & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(6).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(6).Text, "NULL") & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(7).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(7).Text), 0)) & "')")
ctr = ctr + 1
orderby = orderby + 1
Loop
Next

You are inserting duplicates of your records because you loop two times on the Items collection of your ListView. A first time with the foreach lvi ... Next statement and a second time with the Do While loop
A full answer to your question would require to introduce you to parameterized queries, but this involves to change radically your Execute method.
So for the immediate answer
Dim orderby = 0
For Each lvi As ListViewItem In lvReportFormat2.Items
Label1.Text = lvi.SubItems(4).Text
Execute("INSERT INTO tblrptChad "& _
"(accountcode,accountdesc,Type,class,Orderby," & _
"ReportType,Formula,Show) VALUES " & _
"('" & _
If(lvi.SubItems(0).Text IsNot DBNull.Value, _
lvi.SubItems(0).Text, "NULL") & "','" & _
If(lvi.SubItems(1).Text IsNot DBNull.Value, _
lvi.SubItems(1).Text, "NULL") & "','" & _
If(lvi.SubItems(2).Text IsNot DBNull.Value, _
lvi.SubItems(2).Text, "NULL") & "','" & _
If(lvi.SubItems(3).Text IsNot DBNull.Value, _
lvi.SubItems(3).Text, "NULL") & "','" & _
orderby & "','" & _
Val(If(lvi.SubItems(5).Text IsNot DBNull.Value, _
Val(lvi.SubItems(5).Text), 0)) & "','" & _
If(lvi.SubItems(6).Text IsNot DBNull.Value, _
lvi.SubItems(6).Text, "NULL") & "','" & _
Val(If(lvi.SubItems(7).Text IsNot DBNull.Value, _
Val(lvi.SubItems(7).Text), 0)) & "')")
orderby = orderby + 1
Next
lvi in the for each is the ListViewItem currently indexed.
This means that lvi is lvReportFormat2.Items(ctr)
As a side note, I am pretty sure that a string property like SubItems(x).Text cannot be a DBNull value, so all these IIF are pretty useless and can be removed. I let you try it.
Said that, you really should look at parameterized queries to simplify your command text removing all those string concatenations that are error prone to get it right (for example, did yuo check what happens if one of your subitems contains a text with an apostrophe?) and are the main vector for Sql Injection attacks.

TO SOLVE THE PROBLE YOU JUST NEED TO ADD "EXIT SUB" OUTSIDE THE LOOP
For Each lvi As ListViewItem In lvReportFormat2.Items
Dim count = lvReportFormat2.Items.Count
Dim ctr = 0
Dim orderby = 0
label.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Do While ctr < count
Label1.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Execute("INSERT INTO tblrptChad (accountcode,accountdesc,Type,class,Orderby,ReportType,Formula,Show)VALUES ('" & IIf(lvReportFormat2.Items(ctr).SubItems(0).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(0).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(1).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(1).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(2).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(2).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(3).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(3).Text, "NULL") & "','" & orderby & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(5).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(5).Text), 0)) & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(6).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(6).Text, "NULL") & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(7).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(7).Text), 0)) & "')")
ctr = ctr + 1
orderby = orderby + 1
Loop
EXIT SUB
Next

Related

Insert data into SQL Server using VBA

I'm trying to create a tool that will import an Excel file data into the SQL Server database. The thing is I get an error
Command Text was not set for the command Object
I guess there's something wrong with my "Do While". I tried first simple insert query no error but it saved in SQL Server as blank.
Private Sub CommandButton1_Click()
Dim SourcePath, DestPath, PMatrixPath, FileExists, x
SourcePath = ThisWorkbook.Worksheets("Config").Cells(2, 2).Value
DestPath = ThisWorkbook.Worksheets("Config").Cells(3, 2).Value
Dim Conn As ADODB.connection
Dim rsSql As New ADODB.Recordset
Dim server_name As String, database_name As String
Dim sqlQuery As String
Dim ShtName As String
Dim rw As Integer
If SourcePath = "" Then
SourcePath = Application.GetOpenFilename _
(Title:="Please choose the Daily APAC file", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If SourcePath = False Then
MsgBox "No Daily RAW data File Selected. Please set the path in Config Tab or select here", vbExclamation, "Sorry!"
Exit Sub
End If
End If
FileExists = Dir(SourcePath)
If FileExists = "" Then
MsgBox "Daily RAW data File doesn't exist in the mentioned path", vbExclamation, "Sorry!"
Exit Sub
End If
With Sheets("Sheet1")
Set Conn = New ADODB.connection
Let server_name = "10.206.88.119\BIWFO"
Let database_name = "TESTDB"
Let UserName = "admin"
Let Password = "pass"
Conn.Open "Provider=SQLOLEDB;Data Source=" + server_name & ";Initial Catalog=TESTDB;" + "Uid=" & UserName + "; Pwd=" & Password + ";"
rw = 2
Do While Not .Range("A" & rw).Value = ""
Sheet1.Range("A2").Value = rw
sqlQuery = "Insert into tbl_MN_Daily_SLA values ('" & .Range("A" & rw).Value & "','" & .Range("B" & rw).Value & "','" & .Range("G" & rw).Value & "','" & .Range("AX" & rw).Value & "','" & .Range("I" & rw).Value & "','" & .Range("AU" & rw).Value & "','" & .Range("AV" & rw).Value & "','" & .Range("J" & rw).Value & "','" & .Range("M" & rw).Value & "','" & CDate(.Range("N" & rw).Value) & "','" & CDate(.Range("S" & rw).Value) & "','" & CDate(.Range("T" & rw).Value) & "','" & .Range("AF" & rw).Value & "','" & .Range("C" & rw).Value & "','" & CDate(.Range("U" & rw).Value) & "','" & .Range("V" & rw).Value & "','" & CDate(.Range("X" & rw).Value) & "','" & CDate(.Range("Y" & rw).Value) & "','" & CDate(.Range("AD" & rw).Value) & "','" & CDate(.Range("AE" & rw).Value) & "','" & .Range("L" & rw).Value & "');"
rw = rw + 1
Loop
Debug.Print sqlQuery
rsSql.CursorLocation = adUseClient
rsSql.Open sqlQuery, Conn, adOpenStatic
Conn.Close
Set Conn = Nothing
End With
End Sub

Windows service using VB.NET doesn't work?

What my program supposed to do : My goal is to create a windows service which acts as a mediator between multiple SQL databases. In total there are 3 different tables in 3 different servers In detail, when this service runs it should oversee the data in the "Table1" and copy it to the "Table2" in periodical time(every 1 minute). But tricky part is it cannot paste duplicate records, has to check for "Table2" 's ID field and validate for not pasting the same record with the same ID.I've added a diagram for understanding purposes of what my goal is
What I've done : So far I've developed the code completely but the issue is it only copies data from one table(specifically "NOR_LABOR" according to the diagram I've attached) to "DEV_Test_Nor_Data" in the "MES_DEV" Database(con1 to con2). According to the diagram con1, con3, con4 are tables "NOR_LABOR", "SETTER_LABOR" and "wrap_labor" respectively. con2 is the destination which is "MES_DEV" DB.
Can anybody figure out why does other table's data(con3 to con2 & con4 to con2) won't copy?
My code - Data Collector
Imports System.Configuration
Imports System.Data.SqlClient
Public Class DataCollector
Dim con1, con2, con3, con4 As New SqlConnection
Dim timer1 As Timers.Timer
Dim p_oConn As New Wisys.AllSystem.ConnectionInfo
Protected Overrides Sub OnStart(ByVal args() As String)
con1 = New SqlConnection("Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true")
con1.Open()
con2 = New SqlConnection("Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true")
con2.Open()
con3 = New SqlConnection("Data Source=201706-SETTER1\SQLEXPRESS;Database=Edge;Integrated Security=true")
con3.Open()
con4 = New SqlConnection("Data Source=PRINTER\SQLEXPRESS;Database=Wrapper Data;Integrated Security=true")
con4.Open()
timer1 = New Timers.Timer()
timer1.Interval = 5000
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
con1.Close()
con2.Close()
con3.Close()
con4.Close()
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
Dim cmd1, cmd2, cmd3 As SqlCommand
'Connecting the Normac Data table
Dim da1 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, feet_produced, item_no, posted, labor_feet_produced from NOR_LABOR", con1)
Dim cb1 As SqlCommandBuilder = New SqlCommandBuilder(da1)
Dim dt1 As DataTable = New DataTable()
da1.Fill(dt1)
'Connecting the Setter_Labor table
Dim da2 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, labor_feet_produced, item_no, posted from Setter_Labor", con3)
Dim cb2 As SqlCommandBuilder = New SqlCommandBuilder(da2)
Dim dt2 As DataTable = New DataTable()
da2.Fill(dt2)
'Connecting the Wrap_Labor table
Dim da3 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, Department, work_center, operation_no, operator, total_labor_hrs, job_start, job_end, qty_ordered, qty_produced, item_no, lot_no, default_bin, posted, wrapped, total_shift_hrs, check_emp, machine, operation_complete from wrap_labor", con4)
Dim cb3 As SqlCommandBuilder = New SqlCommandBuilder(da3)
Dim dt3 As DataTable = New DataTable()
da3.Fill(dt3)
Dim i, j, k As Integer
'Inserting into DEV_Test_Nor_Data table
For Each dr As DataRow In dt1.Rows
cmd1 = New SqlCommand("Insert into DEV_Test_Nor_Data values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','" & dr(11) & "')", con2)
i = cmd1.ExecuteNonQuery()
Next
'Inserting into DEV_Test_Set_Lbr table
For Each dr As DataRow In dt2.Rows
cmd2 = New SqlCommand("Insert into DEV_Test_Set_Lbr values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "')", con2)
j = cmd2.ExecuteNonQuery()
Next
'Inserting into DEV_Test_Wrp_Lbr table
For Each dr As DataRow In dt3.Rows
cmd3 = New SqlCommand("Insert into DEV_Test_Wrp_Lbr values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','" & dr(11) & "','" & dr(12) & "','" & dr(13) & "','" & dr(14) & "','" & dr(15) & "','" & dr(16) & "','" & dr(17) & "','" & dr(18) & "','" & dr(19) & "','" & dr(20) & "')", con2)
k = cmd3.ExecuteNonQuery()
Next
da1.Update(dt1)
cmd1.Dispose()
dt1.Dispose()
da1.Dispose()
da2.Update(dt2)
cmd2.Dispose()
dt2.Dispose()
da2.Dispose()
da3.Update(dt3)
cmd3.Dispose()
dt3.Dispose()
da3.Dispose()
End Sub
End Class
Reference2
Reference3
Reference4
See if this helps. It may be the parameterized queries are your entire problem.
Public Class DataCollector
'Question text said one minute
Private timer1 As New Timers.Timer(60000)
Protected Overrides Sub OnStart(ByVal args() As String)
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
' DEV_Test_Nor_Data Table
ProcessOneTable("DEV_Test_Nor_Data", 12,
"Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true",
"SELECT ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, feet_produced, item_no, posted, labor_feet_produced FROM NOR_LABOR"
)
' DEV_Test_Set_Lbr Table
ProcessOneTable("DEV_Test_Set_Lbr", 11,
"Data Source=201706-SETTER1\SQLEXPRESS;Database=Edge;Integrated Security=true",
"SELECT ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, labor_feet_produced, item_no, posted from Setter_Labor"
)
' DEV_Test_Wrp_Lbr Table
ProcessOneTable("DEV_Test_Wrp_Lbr", 21,
"Data Source=PRINTER\SQLEXPRESS;Database=Wrapper Data;Integrated Security=true",
"SELECT ID, trx_date, work_order, Department, work_center, operation_no, operator, total_labor_hrs, job_start, job_end, qty_ordered, qty_produced, item_no, lot_no, default_bin, posted, wrapped, total_shift_hrs, check_emp, machine, operation_complete from wrap_labor"
)
End Sub
Private EdgeConnStr As String = "Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true"
Private Sub ProcessOneTable(destTableName As String, ParameterCount As Integer, sourceConnectionString AS String, sourceSql As String)
Dim data As New DataTable()
Using sourceConn As New SqlConnection(sourceConnectionString), _
da As New SqlDataAdapter(sourceSql, sourceConn)
da.Fill(data)
End Using
Dim paramList As String = String.Join(",", Enumerable.Range(0, ParameterCount).Select(Function(p) $"#p{p}"))
' Assumes first parateter (#p0) is always the ID.
Dim sql As String = $"INSERT INTO {destTableName} SELECT {paramList} WHERE NOT EXISTS(SELECT ID FROM {destTableName} WHERE ID = #p0)"
Using cn As New SqlConnection(EdgeConnStr), _
cmd As New SqlCommand(sql, cn)
For i As Integer = 0 To ParameterCount - 1
cmd.Parameters.Add($"#p{i}", SqlDbType.VarChar)
Next i
cn.Open()
For Each dr As DataRow In data.Rows
For i As Integer = 0 to ParameterCount - 1
cmd.Parameters(i).Value = dr(i)
Next i
cmd.ExecuteNonQuery()
Next dr
End Using
End Sub
End Class
It sounds like you also need to worry about merging the data, but start with this anyway; it fixes the HUGE GAPING SECURITY ISSUE in the original code, as well as isolating the important part of the code down to the minimum possible method size. This will make it easier to refactor just that part to also worry about what IDs may already exist... but I'll let you make an attempt at that yourself first (hint: INSERT + SELECT + WHERE NOT EXISTS() all in the same query)

IF adding record is cancelled then return adding another record

Im having a problem of adding records when I click the messagebox and i answered is no then cancel it and add another record but im having a message of connection has not been initialized heres my code thank you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim reader As SqlDataReader
conn.Open()
Dim bday As String
bday = adyear.Text & "-" & admonth.Text & "-" & adday.Text
If adfirstname.Text.Length < 2 Then
MessageBox.Show("Firstname is too short")
End If
Dim exist As String
exist = "select * from record where firstname='" & adfirstname.Text & "'" & " and lastname='" & adlastname.Text & "';"
cmd = New SqlCommand(exist, conn)
reader = cmd.ExecuteReader
If reader.HasRows = True Then
If MsgBox("THE MEMBER YOU ARE TRYING TO ADD HAS AN SAME FIRSTNAME AND LASTNAME IN THE RECORD DO YOU WISH TO CONTINUE ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
ElseIf adage.Text < 18 Then
If MsgBox("The member is less than 18 years old is this an intern?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim add As String
add = "insert into record(firstname,middlename,lastname,birthday,age,jobposition)" & _
"values(" & _
"'" & adfirstname.Text & "'," & _
"'" & admiddlename.Text & "'," & _
"'" & adlastname.Text & "'," & _
"'" & bday & "'," & _
"'" & adage.Text & "'," & _
"'" & adjobposition.Text & "');"
cmd = New SqlCommand(add, conn)
cmd.ExecuteNonQuery()
MessageBox.Show("Added Complete")
Else
MsgBox("Action is Terminated")
' code for return to adding and stop the messagebox of the connection has not been initialized
End If
End If
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
Well, since it appears the conn is a form level object you would need to call
conn = New SqlConnection(<connection string>)
before you can use it to open the connection. Given that you call
conn.Dispose()
to destroy the conn instance in the Finally block it appears that you do not keep an open connection around for long.

Cause of "Run-time error code '3061' too few parameters. Expected 1."

The following code causes the error "Run-time error code '3061' too few parameters. Expected 1." but I'm not sure why:
Private Sub cmdAdd_Click()
'to add data to table
CurrentDb.Execute "INSERT INTO student(Name, Age, Sex, Email, Mobile, Course, Name_Of_Kin, Relationship, Email_Of_Kin, Mobile_Of_Kin, School_Fees, Qualification) " & _
"VALUES (" & Me.txtName & " ,'" & Me.DTPAge & "','" & Me.cmbSex & "','" & Me.txtEmail & "','" & Me.txtMobile & "','" & Me.cmbCourse & "','" & Me.txtNOK & "','" & Me.cmbROK & "','" & Me.txtEOK & "','" & Me.txtMOK & "','" & Me.cmbFees & "','" & Me.cmbQual & "')"
frmStudentSub.Form.Requery
End Sub
First, have a look here:
Insert record using a recordset
Then, as it seems you insert the record in a table used by an open form, you can use the RecordsetClone of that form:
Private Sub cmdAdd_Click()
Dim rs As DAO.Recordset
Set rs = frmStudentSub.Form.RecordsetClone
rs.AddNew
rs!Name.Value = Me!txtName.Value
rs!Age.Value = Me!DTPAge.Value
rs!Sex.Value = Me!cmbSex.Value
rs!Email.Value = Me!txtEmail.Value
rs!Mobile.Value = Me!txtMobile.Value
rs!Course.Value = Me!cmbCourse.Value
rs!Name_Of_Kin.Value = Me!txtNOK.Value
rs!Relationship.Value = Me!cmbROK.Value
rs!Email_Of_Kin.Value = Me!txtEOK.Value
rs!Mobile_Of_Kin.Value = Me!txtMOK.Value
rs!School_Fees.Value = Me!cmbFees.Value
rs!Qualification.Value = Me!cmbQual.Value
rs.Update
' Not needed.
' frmStudentSub.Form.Requery
Set rs = Nothing
End Sub

Getting Syntax Error on INSERT INTO command on Visual Basic 2010 to MS ACCESS 2007

I keep getting a syntax error when I run a debug on the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles add.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'Open Connection if not yet Open
cnn.Open() End If
cmd.Connection = cnn
If Me.sn.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO First_Year(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX,SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother,Occupation_m,School Last Attended,Address School,Middle_Name)" +
"VALUES ('" & Me.sn.Text & "','" & Me.fn.Text & "','" & Me.ln.Text & "' ,'" & Me.Year.Text & "','" & Me.ed.Value & "','" & Me.s.Text & "','" & Me.sy.Text & "','" & Me.cs.Text & "','" & Me.re.Text & "'," & Me.cn.Text & ",'" & Me.bd.Value & "','" & Me.fa.Text & "','" & Me.fo.Text & "','" & Me.ma.Text & "','" & Me.mo.Text & "','" & Me.lad.Text & "','" & Me.ad.Text & "','" & Me.mi.Text & "')"
cmd.ExecuteNonQuery()
Can some please point out to me whats wrong with it?
You have some fields name that contains spaces. To use these fields names you need to enclose them in square brackets
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"...... "
Said that, remember that string concatenations like yours lead to Sql Injection and problem in parsing strings that contains quotes (O'Brien) or decimal numbers or date
Search about Sql Injection and Parameterized queries
A parameterized approach to your query would be
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("#p1", Me.sn.Text)
cmd.Parameters.AddWithValue("#p2", Me.fn.Text)
... and so on for the remainder 16 parameters placeholders
... respecting their position and converting to the appropriate datatype
you need to remove the space here (in your query) :
......School Last Attended,Address School.......
or write it like this :
..........[School Last Attended],[Address School]..........

Resources