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
Related
Private Sub submit_btn_Click(sender As System.Object, e As System.EventArgs) Handles submit_btn.Click
Dim connection As New SqlConnection("Server= DESKTOP-56RQL1O\SQLEXPRESS; Database = studdb;Integrated Security = true")
Dim query As String = "INSERT INTO student_register (name, regno,dob,blood,gender,course,phone,email,photo,fname,foccupation,mname,moccupation,address,state1,country1,annual_income,alter_email,alter_phone,tenth_institute,tenth_per,tenth_year,plustwo_intitute,plustwo_per,plustwo_year,degree_university,degree_per,degree_year,college_name,state2,country2) Values ('" & TextBox1.Text & "','" & TextBox2.Text & "'," & DateTimePicker1.Value & ",'" & blood_combo.Text & "','" & gender_combo.Text & "','" & course_combo.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','#photo','" & TextBox8.Text & "','" & TextBox9.Text & "','" & TextBox7.Text & "','" & TextBox6.Text & "','" & TextBox10.Text & "','" & states_combo.Text & "','" & country_combo.Text & "','" & TextBox5.Text & "','" & TextBox12.Text & "','" & TextBox11.Text & "','" & TextBox20.Text & "','" & TextBox16.Text & "','" & TextBox13.Text & "','" & TextBox19.Text & "','" & TextBox18.Text & "','" & TextBox21.Text & "','" & TextBox15.Text & "','" & TextBox17.Text & "','" & TextBox22.Text & "','" & TextBox14.Text & "','" & state2_combo.Text & "','" & country2_combo.Text & "')"
Dim command As New SqlCommand(query, connection)
connection.Open()
command.ExecuteNonQuery()
If (command.ExecuteNonQuery().Equals(1)) Then
MsgBox("Information stored in database")
Else
MsgBox("Not stored in database")
End If
connection.Close()
End Sub
End Class
This is my code for save button. But when I execute this, I am getting an error on the connection.open() line of code:
Cannot open database "studdb" requested by the login. The login failed.
Login failed for user 'DESKTOP-56RQL1O\AARTI PRAMOD'.
Please help me with this.
Cannot open database "studdb" requested by the login. The login failed. Login failed for user 'DESKTOP-56RQL1O\AARTI PRAMOD'.
This normally means that the target database doesn't exist. So using SSMS connect to the SQL Instance and verify that the database exists and that you can access it.
How can I update my access database in vb.net code I use OleDb connection to the database it's make change in datagridview but not into the database
Public Sub executquery()
Dim commandOleDb As New OleDbCommand(query, con)
commandOleDb.ExecuteNonQuery()
con.Close()
End Sub
--------------------
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs)
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Almaashat.accdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO Techers (File_ID,Name,Workplace,Jop,Appointment,Class,Birthday,End_date,End_class,End_for,Note) VALUES (" & TextBoxFile_ID.Text & " ,'" & TextBoxName.Text & "' ,'" & TextBoxWorkplace.Text & "' ,'" & TextBoxJop.Text & "' ,'" & DateTimePickerAppoiment.Text & "','" & TextBoxClass.Text & "','" & DateTimePickerBirthday.Text & "' ,'" & DateTimePickerEnd_date.Text & "' ,'" & TextBoxEnd_class.Text & "','" & TextBoxEnd_for.Text & "' ,'" & TextBoxNote.Text & "')"
executquery()
con.Close()
MsgBox("Your Data Inserted")
Catch ex As Exception
MsgBox("Your Data Not Inserted")
End Try
TechersDataGridView.DataSource = TechersBindingSource
End Sub
You have the definition of string 'query' and OleDBConnection 'con' only in your private Sub executquery
So to correct that :
Public Sub executquery(query as String, con as OleDBConnection)
Dim commandOleDb As New OleDbCommand(query, con)
con.Open()
commandOleDb.ExecuteNonQuery()
con.Close()
End Sub
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs)
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Almaashat.accdb")
Dim query As String
Try
query = "INSERT INTO Techers (File_ID,Name,Workplace,Jop,Appointment,Class,Birthday,End_date,End_class,End_for,Note) VALUES (" & TextBoxFile_ID.Text & " ,'" & TextBoxName.Text & "' ,'" & TextBoxWorkplace.Text & "' ,'" & TextBoxJop.Text & "' ,'" & DateTimePickerAppoiment.Text & "','" & TextBoxClass.Text & "','" & DateTimePickerBirthday.Text & "' ,'" & DateTimePickerEnd_date.Text & "' ,'" & TextBoxEnd_class.Text & "','" & TextBoxEnd_for.Text & "' ,'" & TextBoxNote.Text & "')"
executquery(query,con)
MsgBox("Your Data Inserted")
Catch ex As Exception
MsgBox("Your Data Not Inserted")
End Try
TechersDataGridView.DataSource = TechersBindingSource
End Sub
I've got the following piece of code in a Windows form, but I'm getting an error
Overload resolution failed because no accessible 'ExecuteNonQuery' accepts this number of arguments
I've searched around and everything I see seems to relate to the number of parameters. I'm supplying the number the code is expecting (43), can anyone point me in the right direction?
Public Class wfRecDB
Dim cn As New SqlConnection("Data Source=.;Initial Catalog=RecDb;Provider=SQLNCLI11.1;Integrated Security=SSPI;Auto Translate=False;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private Sub wfRecDB_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmd.Connection = cn
End Sub
Private Sub btnCon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCon.Click
If cbEnv.Text <> "" Then
cn.Open()
cmd.CommandText = "insert into recdb.recs.recdbextract (Environment,Unreconciled,Reconciled,Account,AcctRel,AccInc,AcctPro,Address,AssClass,BankAcc,BrkRel,CBNwork,CCTE,CIB,ClCont,ClCparty,ClFatca,ClFatcaDet,ExtRef,FamGp,FundLd,GenVar,IsaDec,LocStr,MPLocPat,MPOutPat,MPPatDet,MPPatHead,MPProdPat,NomAcc,NomAccLink,OutAssCl,OutMktCam,SippAcc,SippBCE,SippBenReq,SippLta,SippPaye,SippPenInc,SippRegPay,UnitPrice,UserGroups,UserPerms) values ('" & cbEnv.Text & "','" & rbUnreconciled.Text & "','" & rbReconciled.Text & "','" & cbAccount.Text & "', '" & cbAccountRelationship.Text & " ','" & cbAccountIncomeDistributionChoice.Text & "','" & cbAccountProfile.Text & "','" & cbAddress.Text & "','" & cbAssetClassification.Text & "','" & cbBankAccount.Text & "','" & cbBrokerRelationship.Text & "','" & cbClientBroker.Text & "','" & cbClientCorp.Text & "','" & cbClientInd.Text & "','" & cbClientContext.Text & "','" & cbClientCparty.Text & "','" & cbClientFATCA.Text & "','" & cbClientFATCADetails.Text & "','" & cbExtRefPlfmOne.Text & "','" & cbFamilyGroups.Text & "','" & cbFundLoader.Text & "','" & cbGenericVariables.Text & "','" & cbIsadec.Text & "','" & cbLocationStructure.Text & "','" & cbtbMPLocation.Text & "','" & cbMPOut.Text & "','" & cbPatDet.Text & "','" & cbPatHead.Text & "','" & cbProd.Text & "','" & cbNomAcc.Text & "','" & cbNomAccLink.Text & "','" & cbAssetClassification.Text & "','" & cbOutCam.Text & "','" & cbSIPPAcc.Text & "','" & cbSIPPBCE.Text & "','" & cbSIPPBen.Text & "','" & cbSIPPLTA.Text & "','" & cbSIPPPAYE.Text & "','" & cbSIPPPen.Text & "','" & cbSIPPReg.Text & "','" & cbUnitPrice.Text & "','" & cbUserGroups.Text & "','" & cbUserPerm.Text & "')"
cmd.ExecuteNonQuery("")
cn.Close()
cbEnv.Text = ""
rbUnreconciled.Text = ""
rbReconciled.Text = ""
End If
End Sub
The error is very clear - there's no overload of ExecuteNonQuery() that takes a single string parameter as you're supplying here:
cmd.ExecuteNonQuery("")
ExecuteNonQuery() expects no parameters - so just change that line of code to
cmd.ExecuteNonQuery()
and you should be fine.
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
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]..........