I am filling data from a sheet of Excel book to datatable . The excel sheet contains about 160 columns. It gives error message "to many fields"
Dim largespan1 As String
Dim larg As String
Dim str, str5, str6 As String
largespan1 = "C:\shivam.xls"
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & largespan1 & ";Extended Properties=""Excel 8.0;HDR=yes;IMEX=1"""
Dim len, len1, i As Integer
Dim cmd, cmd1 As New SqlCommand()
Dim objConn1 As New OleDbConnection(sConnectionString)
Dim objCmdSelect1 As New OleDbCommand("SELECT * FROM [Master Schedule1$]", objConn1)
objConn1.Open()
Dim objAdapter2 As New OleDbDataAdapter()
objAdapter2.SelectCommand = objCmdSelect1
Dim dt5 As New DataTable
objAdapter2.Fill(dt5)
objConn1.Close()
Any one can suggest why it happens
Thanks in advance
Related
i need store the value "IdMaterial" from table 1 ( imagine that have more that 40 records) into a array save all that reacord into table 2 on the code i will show you only save me the first record and not all.
i will apreceate your help i a noobie in proraming
Code :
Dim i As Integer
i = 0
Try
Dim mater As String
Dim planta As String
Dim almacen As String
Dim lot As String
Dim cantidad As String
Dim cantadiat As String
Dim undad As String
Dim Cantidadc As String
Dim CantidadB As String
Dim Session1 As String
Dim fecha As String
'''''
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Using CustCommand As New SqlCommand(editCustQuery, Con34)
Dim dr As SqlDataReader = CustCommand.ExecuteReader()
dr.Read()
mater = dr.GetString(0)
planta = dr.GetString(1)
almacen = dr.GetString(2)
lot = dr.GetString(3)
cantidad = dr.GetString(4)
cantadiat = dr.GetString(5)
undad = dr.GetString(6)
Cantidadc = dr.GetString(7)
CantidadB = dr.GetString(8)
Session1 = dr.GetString(9)
fecha = dr.GetDateTime(10)
end using
Dim Con As New Data.SqlClient.SqlConnection
Dim StrSQL As String
Con.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL = ""
StrSQL = "EXEC P_AsigDupla '" & Txtfecha.Text & "','" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "','" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater & "', '" & lot & "'"
Con.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL, Con)
CmdAd.ExecuteNonQuery()
Con.Close()
i = i + 1
'Next
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
First of all if I understand correctly, you want to put the information of those 40 rows and multiple columns into multiple arrays. If that is true then you are missing () when declaring the arrays.
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim RowCounter as Integer = 0
Second I will approach this different. I will run the query and put the result into a DataTable. Then with a For go through each row and start filling the arrays.
MySQLOpenConnection()
Dim MySQLExecute As New MySqlCommand(MySQLCommand, MySQLConnection)
Dim MySQLAdapter As MySqlDataAdapter = New MySqlDataAdapter(MySQLExecute)
Dim TableResult As New DataTable("QueryResult")
MySQLAdapter.Fill(TableResult)
MySQLCloseConnection()
For each tablerow as DataRow in TableResult.Rows
mater(RowCounter) = TableResult.Rows.Item(RowCounter).Item(0)
planta(RowCounter) = TableResult.Rows.Item(RowCounter).Item(1)
almacen(RowCounter) = TableResult.Rows.Item(RowCounter).Item(2)
lot(RowCounter) = TableResult.Rows.Item(RowCounter).Item(3)
cantidad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(4)
cantadiat(RowCounter) = TableResult.Rows.Item(RowCounter).Item(5)
undad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(6)
Cantidadc(RowCounter) = TableResult.Rows.Item(RowCounter).Item(7)
CantidadB(RowCounter) = TableResult.Rows.Item(RowCounter).Item(8)
Session1(RowCounter) = TableResult.Rows.Item(RowCounter).Item(9)
fecha(RowCounter) = TableResult.Rows.Item(RowCounter).Item(10)
RowCounter=RowCounter+1
Next
The comment did not have enough characters for the answer for the second issue so here it goes.
Ok, I see you are using values from the array mater, and lot, but you have to define which one of the values inside the array.
mater() and lot() are as long as the amount of rows of the of the table in the database. So if you have 20 rows on that table, the array lot will have 20 elements going from lot(0) to lot(19) and the same for the others.
If you need to get resultado for each row, then you have to define resultado() as an array and use the same FOR to fill it.
resultado(RowCounter)=GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter)
I hope this solve your issue.
If I Debug this I just get a Invalid Columnname Error("Name of the Object"). I am using a SQL database.
Protected Sub ddlKunden_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlKunden.SelectedIndexChanged
Dim strSql As String
Dim kontakt As String = ddlKunden.SelectedItem.Value
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.ConnectionString = strConnection
connection.Open()
'Kontaktpersonen laden
strSql = "SELECT * FROM Kontaktpersonen WHERE Nr =" & Chr(34) & kontakt & Chr(34)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbP)
End Using
ddlKontaktperson.Items.Clear()
ddlKontaktperson.DataSource = dtbP
ddlKontaktperson.DataTextField = "AP_Nam"
ddlKontaktperson.DataValueField = "ID"
ddlKontaktperson.DataBind()
End Using
ddlKontaktperson.Visible = True
End Sub
The Error pops at
dad.fill(dtbP)
It should select all rows Where Nr="SELECTED VALUE" and you select it in a dropdownlist. And all these rows should be saved in a Datatable then and are used in another dropdownlist.
It works when I try the exact same thing without the where.
Example:
'Kunden laden
strSql = "SELECT * FROM Kontakte"
dtbK = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbK)
End Using
ddlKunden.Items.Clear()
ddlKunden.DataSource = dtbK
ddlKunden.DataTextField = "Nr"
ddlKunden.DataValueField = "Nr"
ddlKunden.DataBind()
Please try following code
You do not need to use "'" around parameters
Just add these values as a parameter to the oledbcommand with its value and type
Otherwise, your sql command will be vulnerable to sql injection
Dim strConnection As String = "Provider=sqloledb;Data Source=(local);" &
"Initial Catalog=kodyaz;" &
"User Id=sa;Password=sa"
Dim kontakt As Int32 = 1
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = connection
cmd.CommandText = "SELECT * FROM Kontaktpersonen WHERE Nr = ?"
cmd.Parameters.AddWithValue("Nr", kontakt)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtbP)
End Using
End Using
I'm not getting my GridViewUpdateEventArgs to work for some reason.
I'm trying to update my gridview(table in sql) but it´s not working.
And i don´t know how to write the the Where clause in the sql to match.
Public Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim SelectRow As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim RowID As HiddenField = Gridview1.FindControl("ID")
Dim Report As String = SelectRow.Cells(1).Text
Dim BusinessArea As String = SelectRow.Cells(2).Text
Dim Salesdepartment As String = SelectRow.Cells(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim SqlCommand As New SqlCommand("UPDATE TEST SET Report = ('" & Report & "'), [Business Area] = ('" & BusinessArea & "'), Salesdepartment = ('" & Salesdepartment & "') WHERE ID = #RowID ", SqlConnection)
Dim SqlDataAdapter As New SqlDataAdapter(SqlCommand)
Dim dataSet As New DataSet()
SqlDataAdapter.Fill(dataSet)
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
The "ID" column is my PK in the table and is in a (ItemTemplate) (Hidden)
In this Way SqlDataAdapter can't update database record, see here how to update record using SqlDataAdapter .
or you can try like this:
Dim row As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim hf As HiddenField = TryCast(row.FindControl("ID"), HiddenField)
Dim Report As [String] = row.Cell(1).Text
Dim BusinessArea As [String] = row.Cell(2).Text
Dim Salesdepartment As [String] = row.Cell(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim cmd As New SqlCommand("UPDATE TEST SET Report = #Report,[Business Area] =#BusinessArea, Salesdepartment=#Salesdepartment WHERE ID = #RowID ", SqlConnection)
cmd.Parameters.AddWithValue("#Report", Report)
cmd.Parameters.AddWithValue("#BusinessArea", BusinessArea)
cmd.Parameters.AddWithValue("#Salesdepartment", Salesdepartment)
cmd.Parameters.AddWithValue("#RowID", hf.Value)
cmd.ExecuteNonQuery()
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
I am able to get sqlbulkcopy working well on iis6(testing server) and iis7(live server) but when uploading the data in iis7, the rows are cut off. It only imports ~190,000 out of 250000 in iis7. In iis 6 using the same code/page it loads all 250000 records without issues. Also both servers are updating the same SQL DB.
I have searched all over for a solution. Any help is much appreciated.
Sub UpdateData()
Dim sSQLTable As String = "Table1"
Dim sExcelFileName As String = savePath
Dim sWorkbook() As String = GetExcelSheetNames(sExcelFileName)
'Create our connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sExcelFileName & ";Extended Properties=""Excel 12.0;HDR=YES;"""
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(ConnString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)
OleDbConn.Open()
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & sWorkbook(0) & "]"), OleDbConn)
Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString, SqlBulkCopyOptions.UseInternalTransaction)
bulkCopy.BulkCopyTimeout = 2000
bulkCopy.DestinationTableName = sSQLTable
'DEMO bulkCopy.ColumnMappings.Add("Excel", "SQL")
bulkCopy.ColumnMappings.Add("Material", "Material")
bulkCopy.ColumnMappings.Add("Plnt", "Plant")
bulkCopy.ColumnMappings.Add("SLoc", "SLoc")
bulkCopy.ColumnMappings.Add("S", "S")
bulkCopy.ColumnMappings.Add("Batch", "Batch")
bulkCopy.ColumnMappings.Add("Special Stock Number", "SpecialStockNumber")
bulkCopy.ColumnMappings.Add("Material Description", "MatDesc")
bulkCopy.ColumnMappings.Add("Typ", "Type")
bulkCopy.ColumnMappings.Add("StorageBin", "StorageBin")
bulkCopy.ColumnMappings.Add("Available stock", "AvailStock")
bulkCopy.ColumnMappings.Add("BUn", "BUn")
'bulkCopy.ColumnMappings.Add("GR Date", "GRDate")
bulkCopy.WriteToServer(dr)
OleDbConn.Close()
End Sub
Thanks Andy for the ExcelDataReader tip!
Got it to work with ExcelDataReader. Looks like it was a memory issue with OleDB. Posting my code in case it will help others in future.
Sub updateData()
Dim sSQLTable As String = "Table1"
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(ConnString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
Dim stream As FileStream = File.Open(savePath, FileMode.Open, FileAccess.Read)
'1. Reading from a binary Excel file ('97-2003 format; *.xls)
'Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateBinaryReader(stream)
'2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
'3. DataSet - The result of each spreadsheet will be created in the result.Tables
'Dim ds As DataSet = excelReader.AsDataSet()
'4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = True
Dim ds As DataSet = excelReader.AsDataSet()
Dim sourceData As New DataTable()
sourceData = ds.Tables(0)
''5. Data Reader methods
'Using destinationConnection As New SqlConnection(ConnString)
' open the connection
'destinationConnection.Open()
'Using bulkCopy As New SqlBulkCopy(destinationConnection.ConnectionString)
' column mappings
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString, SqlBulkCopyOptions.UseInternalTransaction)
bulkCopy.BulkCopyTimeout = 2000
bulkCopy.DestinationTableName = sSQLTable
'DEMO bulkCopy.ColumnMappings.Add("Excel", "SQL")
bulkCopy.ColumnMappings.Add("Material", "Material")
bulkCopy.ColumnMappings.Add("Plnt", "Plant")
bulkCopy.ColumnMappings.Add("SLoc", "SLoc")
bulkCopy.ColumnMappings.Add("S", "S")
bulkCopy.ColumnMappings.Add("Batch", "Batch")
bulkCopy.ColumnMappings.Add("Special Stock Number", "SpecialStockNumber")
bulkCopy.ColumnMappings.Add("Material Description", "MatDesc")
bulkCopy.ColumnMappings.Add("Typ", "Type")
bulkCopy.ColumnMappings.Add("StorageBin", "StorageBin")
bulkCopy.ColumnMappings.Add("Available stock", "AvailStock")
bulkCopy.ColumnMappings.Add("BUn", "BUn")
'bulkCopy.ColumnMappings.Add("GR Date", "GRDate")
'bulkCopy.DestinationTableName = sSQLTable
bulkCopy.WriteToServer(sourceData)
'6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close()
End Sub
I have access db with 3 different tables,I want to load the whole database into dataset so I will be able to work with the data without load the db serval times.
all the examples of working with dataset are showing how to get part of the database using ".fill"
for example :
OleDbCommand CommandObject = new OleDbCommand ("Select * from employee");
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
myDataAdapter.SelectCommand = CommandObject;
myDataAdapter.Fill (myDataSet, "EmployeeData");
this example load only from employee but how can I etrieve the all tables in once into dataset?
in xml for instance there is command to load all the document to dataset with:" dataset.ReadXml"
How can I achive it in access db?
Thanks for any help
Baaroz
Protected Function getDataSetAndFill(ByRef connection As OleDb.OleDbConnection,
Optional ByVal isExportSchema As Boolean = True) As DataSet
Dim myDataSet As New DataSet
Dim myCommand As New OleDb.OleDbCommand
Dim myAdapter As New OleDb.OleDbDataAdapter
myCommand.Connection = connection
'Get Database Tables
Dim tables As DataTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'iterate through all tables
Dim table As DataRow
For Each table In tables.Rows
'get current table's name
Dim tableName As String = table("TABLE_NAME")
Dim strSQL = "SELECT * FROM " & "[" & tableName & "]"
Dim adapter1 As New OleDb.OleDbDataAdapter(New OleDb.OleDbCommand(strSQL, connection))
adapter1.FillSchema(myDataSet, SchemaType.Source, tableName)
'Fill the table in the dataset
myCommand.CommandText = strSQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myDataSet, tableName)
Next
''''''''''''''''''''''''''''''''''''''
'''' Add relationships to dataset ''''
''''''''''''''''''''''''''''''''''''''
'First, get relationships names from database (as well as parent table and child table names)
Dim namesQuery As String = "SELECT DISTINCT szRelationship, szReferencedObject, szObject " & _
"FROM MSysRelationships"
Dim namesCommand As New System.Data.OleDb.OleDbCommand(namesQuery, connection)
Dim namesAdapter As New System.Data.OleDb.OleDbDataAdapter(namesCommand)
Dim namesDataTable As New DataTable
namesAdapter.Fill(namesDataTable)
'Now, get MSysRelationship from database
Dim relationsQuery As String = "SELECT * FROM MSysRelationships"
Dim command As New System.Data.OleDb.OleDbCommand(relationsQuery, connection)
Dim adapter As New System.Data.OleDb.OleDbDataAdapter(command)
Dim relationsDataTable As New DataTable
adapter.Fill(relationsDataTable)
Dim relationsView As DataView = relationsDataTable.DefaultView
Dim relationName As String
Dim parentTableName As String
Dim childTablename As String
Dim row As DataRow
For Each relation As DataRow In namesDataTable.Rows
relationName = relation("szRelationship")
parentTableName = relation("szReferencedObject")
childTablename = relation("szObject")
'Keep only the record of the current relationship
relationsView.RowFilter = "szRelationship = '" & relationName & "'"
'Declare two arrays for parent and child columns arguments
Dim parentColumns(relationsView.Count - 1) As DataColumn
Dim childColumns(relationsView.Count - 1) As DataColumn
For i As Integer = 0 To relationsView.Count - 1
parentColumns(i) = myDataSet.Tables(parentTableName). _
Columns(relationsView.Item(i)("szReferencedColumn"))
childColumns(i) = myDataSet.Tables(childTablename). _
Columns(relationsView.Item(i)("szColumn"))
Next
Dim newRelation As New DataRelation(relationName, parentColumns, childColumns, False)
myDataSet.Relations.Add(newRelation)
Next
If isExportSchema Then
Dim schemaName = GetXmlSchemaFileName()
If File.Exists(schemaName) Then File.SetAttributes(schemaName, FileAttributes.Normal)
myDataSet.WriteXmlSchema(schemaName)
End If
Return myDataSet
End Function
You should just call the OleDbDataAdapter.Fill method with different SelectCommands and pass the same DataSet but different table names inside. In this case, your dataSet will contain different filled tables.