I have a problem when i m rum my code then error is occured "missing semicolon at end of sql statement."
My code is :
Code
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/mssl2.accdb;Persist Security Info=False";);
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string sql = "INSERT INTO digital(Product_Name, Product_Code, Product_Price, Product_Image, Product_Description) VALUES(#pnm, #pcod, #ppr, #pimg, #pdes) SELECT ##IDENTITY;";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#pnm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#pcod", txt_productcode.Text.Trim());
cmd.Parameters.AddWithValue("#ppr", txt_productprice.Text.Trim());
cmd.Parameters.AddWithValue("#pdes", txt_productdescri.Text.Trim());
cmd.Parameters.AddWithValue("#pimg", imgByte);
int Id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", Id);
conn.Close();
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
}
}
}
add semicolon before select ##identity. then try to excute. which means for insert statement one semicolon and for select on semi colon.
Before "SELECT ##IDENTITY", you need a semi-colon.
Technically you're creating two SQL statements.
One for insert, and one for SELECT ##IDENTITY. That's why you need a semi-colon between those two queries.
Related
I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}
OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);
ACCESS 2013 database and i have 2 table 1 for user and table 2 for books i want to display all books that have been taken by user 1 and already did it i want to ask why there are error in query in visual studio and it works fine in MS-ACCESS 2013 query builder the database are in this link and u will find the query result image and display me no value required for parameter i think i did everything gd.
Database link
OleDbConnection connection = new OleDbConnection(#"");
OleDbCommand command = connection.CreateCommand();
OleDbDataReader reader;
try
{
string R = "SELECT * FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.Relation WHERE Table1.ID = 1";
command.CommandText = R;
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ID1.Text = reader["Table1.ID"].ToString();
fName.Text = reader["FirstName"].ToString();
lName.Text = reader["LastName"].ToString();
ID2.Text = reader["Table2.ID"].ToString();
book.Text = reader["Book"].ToString();
}
}
reader.Close();
connection.Close();
}
catch (Exception x)
{
connection.Close();
MessageBox.Show(x.Message.ToString());
}
finally
{
connection.Close();
}
Hello I'm trying to export my data from a gridview to excel the problem is I have a nvarchar column the have the following barcode: 00373228210001695726 and in excel after export it looks like this 3,73228E+17
my query looks like this:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=AP;Initial Catalog=MGW;User Id=sa;Password=GaUbdFO2;App=EntityFramework;");
try
{
connection.Open();
string sqlStatement = " ";
sqlStatement += " SELECT UserName AS UserID, Site, AddressID, Parameters, Content AS Barcode , TriggerDate, ReceivedDate, Action, DeviceID, Longitude, Latitude, CASE WHEN Latitude != '' THEN 'View Map Location' Else 'No Location' END AS LatitudeMSG FROM RequestWithLocation WHERE";
sqlStatement += " Content = #Content ";
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlStatement += " AND TriggerDate >= #TriggerDateStart AND TriggerDate <= #TriggerDateEnd ";
}
sqlStatement += " ORDER BY TriggerDate DESC";
using (SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection))
{
sqlCmd.Parameters.AddWithValue("#Content", TextBoxSearch.Text);
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlCmd.Parameters.AddWithValue("#TriggerDateStart", Convert.ToDateTime(TextBoxStart.Text));
sqlCmd.Parameters.AddWithValue("#TriggerDateEnd", Convert.ToDateTime(TextBoxEnd.Text).AddDays(+1));
}
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridDisplayData.DataSource = dt;
GridDisplayData.DataBind();
lblError.Text = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found');", true);
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Search timed-out! try again..');", true);
}
EXPORT FUNCTION
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachchment; filename=Report_EventScan.xls; IMEX=1;");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridDisplayData.RenderControl(hw);
//Panel7.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
Use Response.Write("'" + sw.ToString()); to force a prefixed single quotation character in front of the number. That forces Excel to adopt text formatting.
(I'm assuming that + is a string concatenation in your language; it might be &).
I solved my problem. this is what I did:
You can download the EPPlus Excel reader from here http://epplus.codeplex.com/
Then using OfficeOpenXml; on top of your project and the following code to your export button, this should work for everyone who use a DataSet which is saved in a ViewState
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet dt = new DataSet();
dt = (DataSet)ViewState["QueryTable"];
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
foreach (DataTable table in dt.Tables)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("My Excel Report " + i++);
worksheet.Cells["A1"].LoadFromDataTable(table, true);
}
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename= test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
Can OrmLite recognize differences between my POCO and my schema and automatically add (or remove) columns as necessary to force the schema to remain in sync with my POCO?
If this ability doesn't exist, is there way for me to query the db for table schema so that I may manually perform the syncing? I found this, but I'm using the version of OrmLite that installs with ServiceStack and for the life of me, I cannot find a namespace that has the TableInfo classes.
I created an extension method to automatically add missing columns to my tables. Been working great so far. Caveat: the code for getting the column names is SQL Server specific.
namespace System.Data
{
public static class IDbConnectionExtensions
{
private static List<string> GetColumnNames(IDbConnection db, string tableName)
{
var columns = new List<string>();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = "exec sp_columns " + tableName;
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var ordinal = reader.GetOrdinal("COLUMN_NAME");
columns.Add(reader.GetString(ordinal));
}
reader.Close();
}
return columns;
}
public static void AlterTable<T>(this IDbConnection db) where T : new()
{
var model = ModelDefinition<T>.Definition;
// just create the table if it doesn't already exist
if (db.TableExists(model.ModelName) == false)
{
db.CreateTable<T>(overwrite: false);
return;
}
// find each of the missing fields
var columns = GetColumnNames(db, model.ModelName);
var missing = ModelDefinition<T>.Definition.FieldDefinitions
.Where(field => columns.Contains(field.FieldName) == false)
.ToList();
// add a new column for each missing field
foreach (var field in missing)
{
var alterSql = string.Format("ALTER TABLE {0} ADD {1} {2}",
model.ModelName,
field.FieldName,
db.GetDialectProvider().GetColumnTypeDefinition(field.FieldType)
);
Console.WriteLine(alterSql);
db.ExecuteSql(alterSql);
}
}
}
}
No there is no current support for Auto Migration of RDBMS Schema's vs POCOs in ServiceStack's OrmLite.
There are currently a few threads being discussed in OrmLite's issues that are exploring the different ways to add this.
Here is a slightly modified version of code from cornelha to work with PostgreSQL. Removed this fragment
//private static List<string> GetColumnNames(object poco)
//{
// var list = new List<string>();
// foreach (var prop in poco.GetType().GetProperties())
// {
// list.Add(prop.Name);
// }
// return list;
//}
and used IOrmLiteDialectProvider.NamingStrategy.GetTableName and IOrmLiteDialectProvider.NamingStrategy.GetColumnName methods to convert table and column names from PascalNotation to this_kind_of_notation used by OrmLite when creating tables in PostgreSQL.
public static class IDbConnectionExtensions
{
private static List<string> GetColumnNames(IDbConnection db, string tableName, IOrmLiteDialectProvider provider)
{
var columns = new List<string>();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = getCommandText(tableName, provider);
var tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
for (int i = 0; i < tbl.Columns.Count; i++)
{
columns.Add(tbl.Columns[i].ColumnName);
}
}
return columns;
}
private static string getCommandText(string tableName, IOrmLiteDialectProvider provider)
{
if (provider == PostgreSqlDialect.Provider)
return string.Format("select * from {0} limit 1", tableName);
else return string.Format("select top 1 * from {0}", tableName);
}
public static void AlterTable<T>(this IDbConnection db, IOrmLiteDialectProvider provider) where T : new()
{
var model = ModelDefinition<T>.Definition;
var table = new T();
var namingStrategy = provider.NamingStrategy;
// just create the table if it doesn't already exist
var tableName = namingStrategy.GetTableName(model.ModelName);
if (db.TableExists(tableName) == false)
{
db.CreateTable<T>(overwrite: false);
return;
}
// find each of the missing fields
var columns = GetColumnNames(db, model.ModelName, provider);
var missing = ModelDefinition<T>.Definition.FieldDefinitions
.Where(field => columns.Contains(namingStrategy.GetColumnName(field.FieldName)) == false)
.ToList();
// add a new column for each missing field
foreach (var field in missing)
{
var columnName = namingStrategy.GetColumnName(field.FieldName);
var alterSql = string.Format("ALTER TABLE {0} ADD COLUMN {1} {2}",
tableName,
columnName,
db.GetDialectProvider().GetColumnTypeDefinition(field.FieldType)
);
Console.WriteLine(alterSql);
db.ExecuteSql(alterSql);
}
}
}
I implemented an UpdateTable function. The basic idea is:
Rename current table on database.
Let OrmLite create the new schema.
Copy the relevant data from the old table to the new.
Drop the old table.
Github Repo: https://github.com/peheje/Extending-NServiceKit.OrmLite
Condensed code:
public interface ISqlProvider
{
string RenameTableSql(string currentName, string newName);
string GetColumnNamesSql(string tableName);
string InsertIntoSql(string intoTableName, string fromTableName, string commaSeparatedColumns);
string DropTableSql(string tableName);
}
public static void UpdateTable<T>(IDbConnection connection, ISqlProvider sqlProvider) where T : new()
{
connection.CreateTableIfNotExists<T>();
var model = ModelDefinition<T>.Definition;
string tableName = model.Name;
string tableNameTmp = tableName + "Tmp";
string renameTableSql = sqlProvider.RenameTableSql(tableName, tableNameTmp);
connection.ExecuteNonQuery(renameTableSql);
connection.CreateTable<T>();
string getModelColumnsSql = sqlProvider.GetColumnNamesSql(tableName);
var modelColumns = connection.SqlList<string>(getModelColumnsSql);
string getDbColumnsSql = sqlProvider.GetColumnNamesSql(tableNameTmp);
var dbColumns = connection.SqlList<string>(getDbColumnsSql);
List<string> activeFields = dbColumns.Where(dbColumn => modelColumns.Contains(dbColumn)).ToList();
string activeFieldsCommaSep = ListToCommaSeparatedString(activeFields);
string insertIntoSql = sqlProvider.InsertIntoSql(tableName, tableNameTmp, activeFieldsCommaSep);
connection.ExecuteSql(insertIntoSql);
string dropTableSql = sqlProvider.DropTableSql(tableNameTmp);
//connection.ExecuteSql(dropTableSql); //maybe you want to clean up yourself, else uncomment
}
private static String ListToCommaSeparatedString(List<String> source)
{
var sb = new StringBuilder();
for (int i = 0; i < source.Count; i++)
{
sb.Append(source[i]);
if (i < source.Count - 1)
{
sb.Append(", ");
}
}
return sb.ToString();
}
}
MySql implementation:
public class MySqlProvider : ISqlProvider
{
public string RenameTableSql(string currentName, string newName)
{
return "RENAME TABLE `" + currentName + "` TO `" + newName + "`;";
}
public string GetColumnNamesSql(string tableName)
{
return "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + tableName + "';";
}
public string InsertIntoSql(string intoTableName, string fromTableName, string commaSeparatedColumns)
{
return "INSERT INTO `" + intoTableName + "` (" + commaSeparatedColumns + ") SELECT " + commaSeparatedColumns + " FROM `" + fromTableName + "`;";
}
public string DropTableSql(string tableName)
{
return "DROP TABLE `" + tableName + "`;";
}
}
Usage:
using (var db = dbFactory.OpenDbConnection())
{
DbUpdate.UpdateTable<SimpleData>(db, new MySqlProvider());
}
Haven't tested with FKs. Can't handle renaming properties.
I needed to implement something similiar and found the post by Scott very helpful. I decided to make a small change which will make it much more agnostic. Since I only use Sqlite and MSSQL, I made the getCommand method very simple, but can be extended. I used a simple datatable to get the columns. This solution works perfectly for my requirements.
public static class IDbConnectionExtensions
{
private static List<string> GetColumnNames(IDbConnection db, string tableName,IOrmLiteDialectProvider provider)
{
var columns = new List<string>();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = getCommandText(tableName, provider);
var tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
for (int i = 0; i < tbl.Columns.Count; i++)
{
columns.Add(tbl.Columns[i].ColumnName);
}
}
return columns;
}
private static string getCommandText(string tableName, IOrmLiteDialectProvider provider)
{
if(provider == SqliteDialect.Provider)
return string.Format("select * from {0} limit 1", tableName);
else return string.Format("select top 1 * from {0}", tableName);
}
private static List<string> GetColumnNames(object poco)
{
var list = new List<string>();
foreach (var prop in poco.GetType().GetProperties())
{
list.Add(prop.Name);
}
return list;
}
public static void AlterTable<T>(this IDbConnection db, IOrmLiteDialectProvider provider) where T : new()
{
var model = ModelDefinition<T>.Definition;
var table = new T();
// just create the table if it doesn't already exist
if (db.TableExists(model.ModelName) == false)
{
db.CreateTable<T>(overwrite: false);
return;
}
// find each of the missing fields
var columns = GetColumnNames(db, model.ModelName,provider);
var missing = ModelDefinition<T>.Definition.FieldDefinitions
.Where(field => columns.Contains(field.FieldName) == false)
.ToList();
// add a new column for each missing field
foreach (var field in missing)
{
var alterSql = string.Format("ALTER TABLE {0} ADD {1} {2}",
model.ModelName,
field.FieldName,
db.GetDialectProvider().GetColumnTypeDefinition(field.FieldType)
);
Console.WriteLine(alterSql);
db.ExecuteSql(alterSql);
}
}
}
So I took user44 answer, and modified the AlterTable method to make it a bit more efficient.
Instead of looping and running one SQL query per field/column, I merge it into one with some simple text parsing (MySQL commands!).
public static void AlterTable<T>(this IDbConnection db, IOrmLiteDialectProvider provider) where T : new()
{
var model = ModelDefinition<T>.Definition;
var table = new T();
var namingStrategy = provider.NamingStrategy;
// just create the table if it doesn't already exist
var tableName = namingStrategy.GetTableName(model.ModelName);
if (db.TableExists(tableName) == false)
{
db.CreateTable<T>(overwrite: false);
return;
}
// find each of the missing fields
var columns = GetColumnNames(db, model.ModelName, provider);
var missing = ModelDefinition<T>.Definition.FieldDefinitions
.Where(field => columns.Contains(namingStrategy.GetColumnName(field.FieldName)) == false)
.ToList();
string alterSql = "";
string addSql = "";
// add a new column for each missing field
foreach (var field in missing)
{
var alt = db.GetDialectProvider().ToAddColumnStatement(typeof(T), field); // Should be made more efficient, one query for all changes instead of many
int index = alt.IndexOf("ADD ");
alterSql = alt.Substring(0, index);
addSql += alt.Substring(alt.IndexOf("ADD COLUMN")).Replace(";", "") + ", ";
}
if (addSql.Length > 2)
addSql = addSql.Substring(0, addSql.Length - 2);
string fullSql = alterSql + addSql;
Console.WriteLine(fullSql);
db.ExecuteSql(fullSql);
}
I can add rows to my Excel spreadsheet one row at a time, but it is incredibly slow (1 minute for 400 records, even using Prepare). So, I know the Sql is valid and the DataTable is good.
The code that works:
public void InsertFromDataTable(string strSql, DataTable dtTable, string strTableName)
{
if (m_oleDbHandler == null)
{
m_oleDbHandler = new OleDbHandler(m_strConnection);
}
//Do one row at a time since the DataAdapter did not work
foreach (DataRow drRow in dtTable.Rows)
{
OleDbParmCollection cololedbParameters = new OleDbParmCollection();
foreach (DataColumn dcColumn in dtTable.Columns)
{
OleDbParameter odpParameter = new OleDbParameter("#" + dcColumn.ColumnName, drRow[dcColumn.ColumnName]);
odpParameter.ParameterName = "#" + dcColumn.ColumnName;
odpParameter.DbType = OleDbHandler.GetDbType(dcColumn.GetType());
odpParameter.Size = dcColumn.MaxLength;
odpParameter.SourceColumn = dcColumn.ColumnName;
cololedbParameters.Add(odpParameter);
}
m_oleDbHandler.ExecuteCommand(strSql, cololedbParameters, true);
}
}
}
When I try to do the same thing using a DataAdapter, it says it returns 458 rows, but there are no new rows in the spreadsheet. The code that fails:
//DataAdapter version
OleDbParmCollection cololedbParameters = new OleDbParmCollection();
foreach (DataColumn dcColumn in dtTable.Columns)
{
OleDbParameter odpParameter = new OleDbParameter();
odpParameter.ParameterName = "#" + dcColumn.ColumnName;
odpParameter.OleDbType = OleDbHandler.GetOleDbType(dcColumn.GetType());
odpParameter.DbType = OleDbHandler.GetDbType(dcColumn.GetType());
odpParameter.Size = dcColumn.MaxLength;
odpParameter.SourceColumn = dcColumn.ColumnName;
cololedbParameters.Add(odpParameter);
}
m_oleDbHandler.InsertFromDataTable(strSql, dtTable, cololedbParameters, strTableName);
and then:
public int InsertFromDataTable(string strSql, DataTable dtTable, OleDbParmCollection cololeDbParameters, string strTableName)
{
//Set every row as added so that they will be inserted
foreach (DataRow drRow in dtTable.Rows)
{
drRow.SetAdded();
}
//Update the output table
int intRows = -1;
try
{
OleDbCommand oleDbCommand = new OleDbCommand(strSql, OpenConnection());
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
if (oleDbParameter.Value == null)
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else if (string.IsNullOrEmpty(oleDbParameter.Value.ToString()))
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
}
OleDbDataAdapter odaAdapter = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM " + strTableName, OpenConnection()));
odaAdapter.InsertCommand = oleDbCommand;
odaAdapter.MissingMappingAction = MissingMappingAction.Passthrough;
odaAdapter.MissingSchemaAction = MissingSchemaAction.Error;
odaAdapter.TableMappings.Add(strTableName, dtTable.TableName);
foreach (DataColumn dcColumn in dtTable.Columns)
{
odaAdapter.TableMappings[0].ColumnMappings.Add(dcColumn.ColumnName, dcColumn.ColumnName);
}
intRows = odaAdapter.Update(dtTable);
}
catch (OleDbException ex)
{
LogStackTrace();
LogToDb.LogException(ex, LogToDb.c_strAppError);
LogToDb.LogMessage("OleDb error", "OleDbHandler.InsertFromDataTable error", strSql, LogToDb.c_intErrorLevelOleDb);
CancelTransactionAndClose();
throw;
}
finally
{
CloseConnection();
}
return (intRows);
}
Why would I get intRows = 458, but there are no new rows in the Excel file?
EDIT: I just did a test to see what happens if I export to a Microsoft Access .mdb (instead of Excel), and the results tell me something. I get 458 blank rows. so, I suspect I am getting 458 blank rows in Excel. So, now the question is why the rows are all blank.
Got it -- the error was in the section below. This works well for an ExecuteNonQuery, but lousy when there is no data.
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
if (oleDbParameter.Value == null)
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else if (string.IsNullOrEmpty(oleDbParameter.Value.ToString()))
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
}
The corrected code, which works well with both Access and Excel is:
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
There was a second, less serious error. I used
OleDbHandler.GetOleDbType(dcColumn.GetType());
which should have been
OleDbHandler.GetOleDbType(dcColumn.DataType);