Export from Excel to SQL: Login Failed for User - sql

I'm trying to create a function within Excel that will write data to my remote SQL Server database with a click of a button. However, I keep getting an error telling me that that my login failed for user "UserName" (Error 80040e4d).
At first I thought there must be a problem with my User/Login within the database, so I went to the remote desktop, opened SQL Server Management Studio and checked all my permissions, made sure Windows authentication was selected, checked the password etc... Still didn't work.
My User has been given Read and Write permissions, so I tried to import data into Excel from SQL, which did work. So I'm assuming this must be an issue within my VBA code, more specifically, my connection string.
I would appreciate it if someone could take a look over it, and tell me what I'm doing wrong? Or if someone else has had this issue and knows what's causing it?
Here's the code I have:
Sub Button3_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sArtistId, sForename, sSurname, sNationality, sBirthDate, sDeathDate As String
With Sheets("NewArtist")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=tcp:IPADDRESS,1433\SqlServer2008;" & _
"Initial Catalog=DatabaseName;User ID=UserName;Password=PassWord" & _
"Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.Components (ArtistId, Forename, Surname, Nationality, BirthDate, DeathDate) values ('" & sArtistId & "', '" & sForename & "', '" & sSurname & "', '" & sNationality & "', '" & sBirthDate & "', '" & DeathDate & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Artists imported."
conn.Close
Set conn = Nothing
End With
End Sub
Thank you very much!
TW

Integrated Security=SSPI
this parameter in your connection string means you are going to pass your windows principal name as authentication, so the sql login and password are being ignored.
you should remove this name/value pair from the connection string, if you want to use a specified username and password.

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

Update Sharepoint from Excel via ADO connection - Internal name issue

I need to update a SharePoint table which has a field name with Spaces. The field name is called Tracking log
Unfortunately there are lot of reports already created that don't let me recreate this column with a different name, so I need to find a workaround to address this special name.
Lot of blogs point me to revise the internal name and check the name given when it was created, so I checked the List Setting menu for the whole URL path and see the following:
https://sales.acs.com/SMS/_layouts/15/FldEdit.aspx?List=%7B686F9AF9%2DFB64%2D4AD9%2DA268%2D19A057C432DA%7D&Field=Tracking%5Fx0020%5Flog
Below is the script I've put together which runs perfectly fine for any other field without spaces in the name, but not specifically for this one.
Dim sSQL As String
' Build the connection string
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;RetrieveIds=Yes;" & "DATABASE=" & sSHAREPOINT_SITE & ";" & "LIST=" & sDEMAND_ROLE_GUID & ";Authentication=Default;"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection.
With cn
.ConnectionString = sConn
.Open
End With
ID = "12345"
fieldName = "Tracking_x0020_log" 'Display view is "Tracking log", I've tried also with Tracking%5Fx0020%5Flog without luck
FieldValue = "Test"
'sSQL = "SELECT * FROM EMEA_SALES WHERE (APA_number='" & Format(ID, "#") & "');"
sSQL = "UPDATE EMEA_SALES SET " & fieldName & " = '" & FieldValue & "' WHERE (APA_number='" & Format(ID, "#") & "');"
rs.Open sSQL, cn, adOpenDynamic, adLockOptimistic
cn.Close
Set cn = Nothing
End Sub
The error I've got is:
No value given for one or more required parameters.
When I change the fieldname for any other without spaces is run smoothly.
Any clue will be appreciated. Thanks folks!

ASP Error No value given for one or more required parameters

I am receiving the following error on my ASP login
Microsoft JET Database Engine error '80040e10'
No value given for one or more required parameters.
/vdateUsr.asp, line 47
The data is being entered in a form and checked in a Access database. Here is the code:
' variables
dim cnStr
dim rcSet
dim frmUsername
dim frmPassword
dim sqlStr
dim strSQL
'store form input into variables
frmUsername = Request.Form("username")
frmPassword = Request.Form("password")
'create connection and recordset objects
Set cnStr = Server.CreateObject("ADODB.Connection")
Set rcSet = Server.CreateObject("ADODB.Recordset")
' defining database connection (connectionstring.asp)
cnStr.ConnectionString = path
cnStr.Provider = provider
cnStr.open
' execute sql and open as recordset
sqlStr = "Select * From users where [User Name] = ('" & frmUsername & "') and [Password] = ('" + frmPassword + "')"
strSQL="SELECT startup site FROM users WHERE [User Name] = ('" & frmUsername & "') and [Password] = ('" & frmPassword & "')"
' Opens the returned values from the SQL as a recordset, ready for iteration by ASP
'Line 47 below
set rcSet = cnStr.Execute(sqlStr)
Any help would be appreciated.
Thanks in advance
We had this exact error, when loading from Excel to store in SQL Server. The cause was that we used column [F6] which didn't exist in the source Excel (the file format had changed). So, a "parameter" can be a column.

Insert a new row into a SQL SERVER CE 3.5 DB not working but doesn't show any error

I'm trying to do a simple In/out register with Visual Basic 2010.
I created a SQL server 3.5 CE database and in there a table with this structure:
There Id have the propriety Identity = true
I got also this in a module
Dim Var_NombreDB As String = "OlgaDatabase.sdf"
Dim Var_ProveedorDB As String = "Microsoft.SQLSERVER.CE.OLEDB.3.5"
Public Conexion_DB As New OleDb.OleDbConnection("Provider=" & Var_ProveedorDB & ";Data Source=" & Var_NombreDB & ";")
Public SQL_string_conexion As String = ""
Public cmd_Command As New OleDb.OleDbCommand
Public Dr_DataReader As OleDb.OleDbDataReader
I'm opening the database connection correctly and I'm able to see the registers in a DataGridView without problems, but when I try to insert a new register just doesn't work, I got textBoxes (txt_) with the data and after fill them the generated CommandText query is
INSERT INTO MOVIMIENTOS (Tipo, SubTipo, Descripcion, Monto, Saldo, Fecha)
VALUES ('1', '2', '3', 4, 24, GETDATE())
When I try it in the query syntax checker (in Server Explorer) the query is ok, and if I run it a new row is added to the table with the expected data.
But when I try to add new rows in running time even when it shows me the "ALL OK" MsgBox, no register is added to my table, This is the code inside my insert button
cmd_Command.CommandType = CommandType.Text
cmd_Command.Connection = Conexion_DB
SQL_string_conexion = "INSERT INTO MOVIMIENTOS (Tipo, SubTipo, Descripcion, Monto, Saldo, Fecha) "
SQL_string_conexion += "VALUES ('" _
& txt_Tipo.Text & "', '" _
& txt_Subtipo.Text & "', '" _
& txt_Descripcion.Text & "', " _
& txt_Monto.Text & ", " _
& txt_Monto.Text + 20 & ", " _
& "GETDATE()" _
& ")"
cmd_Command.CommandText = SQL_string_conexion
Try
cmd_Command.ExecuteNonQuery()
MsgBox("All OK")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Any idea what I'm doing wrong? I'm thinking it have something to do with the Id column but I'm not sure.
Regards
Look in your bin/debug folder for a copy of the database file with data in it. (Duplicate of many answers here)
Workaround is to not include the sdf file in your project, or specify a full path to the .sdf file.

'if exist' SQL query in VBA with ADODB database connection

I need to uplad data from excel into a database, but I need to check first if there is data in the table for each upload so that I Update or Insert data.
To diferentiate Update or Insert, I'm usign a SQL IF EXIST command, which works okay in SQL. When I try this in Excel VBA I get an error message: "Command text was not set for the command object."
See code below
Dim strSQL As String
Dim Value As String
Dim Reference As String
Set RCconn = New ADODB.Connection
Set TuneCMD = New ADODB.Command
' Establish Recordset
Set Results = New ADODB.Recordset
'Establish a Connection
With RCconn
.Provider = "SQLOLEDB"
.ConnectionString = ConStr
End With
'Open the connection
RCconn.Open
'i Columns
For i = 5 To 10 '16
'j rows
For j = 6 To 60 '145
Value= Sheets("Value").Cells(j, i)
Reference= "W_F/P_" & Sheets("Reference").Cells(j, i)
stringTest = "IF EXISTS (SELECT * FROM UploadTable WHERE Ref = '" & Reference & "') "
stringTest = stringTest & "UPDATE Val "
stringTest = stringTest & "SET Val = '" & Value & "' "
stringTest = stringTest & "where Ref = '" & Reference & "' "
stringTest = stringTest & "Else "
stringTest = stringTest & "INSERT INTO UploadTable (Val , Ref ) "
stringTest = stringTest & "values ('" & Value & "', '" & Reference & "')"
RCconn.Execute strSQL
Next
Next
Set Results = Nothing
RCconn.Close
Set RCconn = Nothing
Is it the case that 'IF EXIST' can not be used in VBA? Is there a work around?
Thanks
ADODB.Connection.Execute sends a pass-through query to your database. It doesn't matter what SQL statement was in that string; if your database can understand it, it will be executed.
So inspect your SQL query again.
Try this:
Put a breakpoint on the line RCconn.Execute strSQL. When the debugger breaks there, inspect the value of strSQL. Copy it and execute in SQL Server Management Studio directly. If that doesn't work, correct your code that builds that string. If it works, then there is some problem with your ConnectionString. In that case, check that the userID and password you are using in the ConnectionString to connect has adequate privileges.