|
I am trying to delete all the quotes from a csv file and then grabbing each line as a row in Access' database. Right now I am stuck after hours of research about the error: No value given for one or more required parameters. | | doank | Check the dbcomm.parameters.cout property beofre calling the command. Probably, you do not have the required number. Something could be wrong in your analyser of line.
Note also that Parameters(5) and (6) have the same name.
| | Bruno VB Express Discover | Make sure all of the column names in your table are spelled correctly and match the names specified in the SQL query. Also, be cautious about using reserved words such as "memo".
I'm not sure whether the duplicate parameter name would cause the problem, as mentioned by the other poster, because these are ignored by the .NET OLEDB provider, but it wouldn't hurt to change it to the correct value (e.g. streetname2).
Paul ~~~~ Microsoft MVP (Visual Basic) | | Paul P Clement IV | Yes all my column names are correct and the error still shows up after I change streetName to streetName2. I am stump. Any other suggestion? I already allow in Access so that each column can insert a null value, is there anything else I should check?
| | doank | Have you checked the Parameter Count before executing the Command to make certain there is a Parameter object for each parameter placeholder (15 total) in the SQL query?
Paul ~~~~ Microsoft MVP (Visual Basic) | | Paul P Clement IV | Yes and dump out the sql string for us as well so we can see the resulting SQL string.
Matt Neerincx [MSFT] | | Matt Neerincx | | I have modified the code to include all the columns inside the database except the (cid column which is a key in the table). I do not want to include some of the columns since they are empty and unused but not sure how to do this | | doank | Where are all of these Parameter Count values coming from? I was only looking for the Parameter Count, for the query in your code, when the exception is generated.
Are you reusing the dbComm object instance?
Paul ~~~~ Microsoft MVP (Visual Basic) | | Paul P Clement IV | I turned the sql parameter count into bold in the above code. Each time
a row is inserted into the database, the parameter count is called. How
do you dump the sql string? Basically I have inserted all null values with space. But for some reason it still said the No value given for one or more required parameters.
| | doank | The Parameter Count should be 22 for every row you insert, since you have 22 placeholders in your query statement. Try calling the Clear method for the Parameters collection before adding parameters for the next row.
Paul ~~~~ Microsoft MVP (Visual Basic) | | Paul P Clement IV | Don't forget to assign DBNull.Value to parameters that you're not using. For example, if you had a 'FirstName' parameter, but you didn't want to specify a value for it, be sure to assign it DBNull.Value instead of Nothing.
Dim firstName As String = Nothing
MyCommand.Parameters("FirstName").Value = DBNull.Value
'instead of
MyCommand.Parameters("FirstName").Value = firstName
| | UsuallyPrettyKnowledgeable | | To Pretty: | | doank | The code in the 'Else' block looks good. However, in your 'If' block, the statement 'DBNull.Value.ToString()' will not work because it will evaluate to a String object. DBNull is a different type of object. But your 'Else' looks promising. If it still doesn't work, you may want to try something like this for all of your parameters:
With dbcomm.Parameters .AddWithValue("@isCustomer", DBNull.Value) .AddWithValue("@followUp", DBNull.Value) .AddWithValue("@customerSince", Date.Today().ToString()) .AddWithValue("@salesPerson", DBNull.Value) .AddWithValue("@companyName", IIf(String.IsNullOrEmpty(line(0)), DBNull.Value, line(0))) .AddWithValue("@jobTitle", IIf(String.IsNullOrEmpty(line(1)), DBNull.Value, line(1))) .AddWithValue("@fullName", IIf(String.IsNullOrEmpty(line(2) & " " & line(3) & " " & line(4)), DBNull.Value, line(2) & " " & line(3) & " " & line(4))) .AddWithValue("@streetName", IIf(String.IsNullOrEmpty(line(5)), DBNull.Value, line(5))) '... And so on...
End With
| | UsuallyPrettyKnowledgeable | The
With dbcomm.Parameters
.AddWithValue( "@isCustomer", "False")
.....
End With
Is inside the While loop and therefore you are adding the parameters over and over.
Add the parameters outside the loop (forget the loop) or place is in a sub for optional use.
Validate the string array length.
Add and set the parameters if the array length is valid
and execute the query
Are you of and running?
| | mokeefe | |
Public Function AddLine(ByVal ConnectionString As String, ByVal Line() As String) As Integer
' Validate data before bothering to do anything else
' This should really happen before calling this method especially as you are
' using a string array which has no name value association
' All you can do isa check the length
If Line.Length < 22 Then
' Throw New System.Exception("Invalid Line")
Exit Function
End If
Dim Result As Integer = 0
Dim cmd As New OleDbCommand
Dim con As New OleDbConnection
' config connection
con.ConnectionString = ConnectionString
' config command
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO [Contactsdb] ([isCustomer], [followUp], [customerSince], [salesPerson], [companyName], [jobTitle], [fullName], [streetName], [streetName2], [cityName], [stateName], [zipCode], [countryName], [telephone], [mobilephone], [fax], [emailAddress], [webpage], [shippingAccount], [creditCard], [cardHolder], [memo])" & _
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
cmd.Parameters.Add( "@ItemID", OleDbType.Integer).Value = Line(ProperIndexinArrayForColumn)
cmd.Parameters.Add( "@SecondParam", OleDbType.VarChar).Value = Line(ProperIndexinArrayForColumn)
'...... More Params
'to allow all commands to be nullable
Dim param As OleDbParameter
For Each param In cmd.Parameters
param.IsNullable = True
Next
' Set parameter values
' Option One
cmd.Parameters( "@ItemID").Value = Line(0)
cmd.Parameters( "@SecondParam").Value = Line(ApproperIndexinArrayForColumn)
' .... more param values
' or
' option two
If Not Line(ApproperIndexinArrayForColumn) = "" Then
cmd.Parameters("@SecondParam").Value = Line(ApproperIndexinArrayForColumn)
End If
' managed execution/ error handling. Very important for the connection.
Try
con.Open()
Result = cmd.ExecuteNonQuery()
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.ToString)
con.Dispose() ' closes and disposes
' place break point on cmd.dispose() to easily review exception. Not above! you may stop execution which doesn't terminate the connection and you can be forced into a system restart due to an access db lock.
cmd.Dispose()
End Try
Return Result
End Function
' Also consider a simple class for your line
' Build and pass this to your line add function instead of a string array
Dim ln As New ItemLine
ln.column1 = "Value from text reader"
Friend Class ItemLine
Friend column1 As String
Friend Column2 As String
End Class
or possibly review usage for (instantiate for each line)
Dim col As System.Collections.Specialized.NameValueCollection | | mokeefe | Hi,
I still have not find the answer yet. I have crippled the code and tried inserting only 1 data. The data is (in csv file):
"First Name","Middle Name","Last Name","Company","Business Street","Business City","Business State","Business Postal Code","Business Country","Business Fax","Business Phone","Company Main Phone","Mobile Phone","E-mail Address","Notes","Web Page" "Merry","","Hwitty","Good Supply","5555 County Line Road","City","CA","91353","United States of America","(945) 475-4789","(909) 5462900",,,"HELLOWORLD@AOL.COM","This should be included within the memo Yes this too
Me too "
The code is:
Public Sub SplitFileToArray() Dim fileName As String, fileDir As String, line As String, sr As StreamReader fileDir = Server.MapPath("App_Import") fileName = "imported.csv" sr = File.OpenText(fileDir & "\" & fileName) Try sr.ReadLine() 'To delete the first row in the csv file which usually used for column's names While sr.Peek() <> -1 line = sr.ReadLine() If line.StartsWith("""") And line.EndsWith("""") Then 'Validate with full quotes InsertLine(line.Split(",")) Else While (Not (line.StartsWith("""") And line.EndsWith(""""))) AnD sr.Peek <> -1 line = line & sr.ReadLine line.Replace(vbCrLf, "<br>") 'lblRowAffected.Text = line.ToString() End While line.Replace(vbCrLf, "<br>") InsertLine(line.Split(",")) End If End While Catch ex As Exception System.Diagnostics.Debug.WriteLine(ex.ToString) errorLabel1.Text = ex.Message.ToString() Finally sr.Close() End Try End Sub Public Sub InsertLine(ByRef line As String()) Dim todayDate = Date.Today.Day() Dim todayMonth = Date.Today.Month() Dim todayYear = Date.Today.Year() Dim dbname = "dbase1.mdb" Dim dbpath = Server.MapPath("access_db") Dim commandStr As String, dbcomm As OleDbCommand Dim conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ dbpath & "\" & dbname) conn.Open() commandStr = "INSERT INTO [Contactsdb] ([isCustomer], [followUp], [customerSince], [salesPerson], [companyName], [jobTitle], [fullName], [streetName], [streetName2], [cityName], [stateName], [zipCode], [countryName], [telephone], [mobilephone], [fax], [emailAddress], [webpage], [shippingAccount], [creditCard], [cardHolder], [memo])" & _ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" dbcomm = New OleDbCommand(commandStr, conn) Try With dbcomm.Parameters .AddWithValue("@isCustomer", DBNull.Value) .AddWithValue("@followUp", DBNull.Value) .AddWithValue("@customerSince", todayMonth & "/" & todayDate & "/" & todayYear) .AddWithValue("@salesPerson", DBNull.Value) .AddWithValue("@companyName", RemoveString(line(0))) .AddWithValue("@jobTitle", RemoveString(line(1))) .AddWithValue("@fullName", RemoveString(line(2) & " " & line(3) & " " & line(4))) .AddWithValue("@streetName", RemoveString(line(5))) .AddWithValue("@streetName2", RemoveString(line(6))) .AddWithValue("@cityName", RemoveString(line(7))) .AddWithValue("@stateName", RemoveString(line(8))) .AddWithValue("@zipCode", RemoveString(line(9))) .AddWithValue("@countryName", RemoveString(line(10))) .AddWithValue("@telephone", RemoveString(line(11))) .AddWithValue("@mobilephone", RemoveString(line(12))) .AddWithValue("@fax", RemoveString(line(13))) .AddWithValue("@emailAddress", RemoveString(line(14))) .AddWithValue("@webpage", RemoveString(line(15))) .AddWithValue("@shippingAccount", DBNull.Value) .AddWithValue("@creditCard", DBNull.Value) .AddWithValue("@cardHolder", RemoveString(line(2) & " " & line(3) & " " & line(4))) .AddWithValue("@memo", RemoveString(line(16))) End With sqlError.Text &= "SQL Count = " & dbcomm.Parameters.Count() & "<br />" dbcomm.ExecuteNonQuery() dbcomm.Parameters.Clear() Catch ex As Exception errorLabel2.Text = ex.Message.ToString() Finally conn.Close() End Try End Sub Public Function RemoveString(ByRef myString As String) As String myStringLabel.Text &= "myString before: " & myString & " - myString after: " & Replace(myString, """", "") & "<br />" myString = myString.Replace("<c>", ",") myString = myString.Replace("<br>", vbCrLf) 'Does not work for some reason Return myString.Replace("""", "") End Function
The error says, Index was outside the bounds of the array. This problem should be easy to those familiar with ASP. I have looked for the error for a few hours now, I cannot find it. Disabled most of my loops, still cannot find it.
| | doank | Nevermind, I just got it. The above code is the correct answer. I forgot I have the old csv files which contains an old column. So whoever needs to import a csv file you can use the above code and change the column names to whatever you want. Thank you for all your help. I wouldn't be able to do it without you guys. 
| | doank |
|