I've been searching but have not found a good example of what i need to accomplish. The title says it all. This is what i have so far:
//gather the report details
DataTable dtReturn = new DataTable();
DataTable dtResults = new DataTable();
string strScript = "";
bool doReturnData = false;
try
{
//this function returns my SQL table in to a datatable dtReturn:
var ii =
Utility.db.Connection.EstablishDBConnection("usp_get_data_recap", dtReturn, null, null, true, 60);
//Clear out table before insert
dtResults = OracleDataPull(9, "TRUNCATE TABLE user.SIGNUP_1");
OracleParameter myparam = new OracleParameter();
OracleCommand mycommand = new OracleCommand();
int n;
//bulk insert to the signup_1 table from the datatable members. Datatable contains the same 4 fields being inserted in to signup_1 on the oracle side:
mycommand.CommandText = "INSERT INTO user.SIGNUP_1 ([ID], [ACCOUNT_NUMBER], [MAIN_CUSTOMER], [SIGNUP_DATE]) VALUES(?)";
mycommand.Parameters.Add(myparam);
for (n = 0; n < 100000; n++)
{
[what do i do here?]
}
}
I am not sure if this is correct, or if there is an easier way, but i need to map dtReturn.Rows[n][0-3] to ID, account_number, main_customer, and signup_date respectively.
Help is very apprecaited! Thanks in advance!
edit:
i tried the suggestion below, but am getting an error with the lambda expression:
"Cannot convert lambda expression to type 'string' because it is not a delegate type" :
var ii =
Utility.db.Connection.EstablishDBConnection("usp_get_data", dtReturn, null, null, true, 60);
dtResults = OracleDataPull(9, "TRUNCATE TABLE user.PR_data");
OracleParameter myparam = new OracleParameter();
OracleCommand mycommand = new OracleCommand();
mycommand.ArrayBindCount = dtReturn.Rows.Count;
mycommand.Parameters.Add(":myparam", OracleDbType.Varchar2, dtReturn.Select(c => c.myparam).ToArray(), ParameterDirection.Input);
mycommand.ExecuteNonQuery();
int n;
mycommand.CommandText = "INSERT INTO user.PR_data ([ID], [ACCOUNT_NUMBER], [MAIN_CUSTOMER], [SIGNUP_DATE]) VALUES(?)";
mycommand.Parameters.Add(myparam);
for (n = 0; n < 100000; n++)
{
myparam.Value = n + 1;
mycommand.ExecuteNonQuery();
}
dtResults = Utility.db.Connection.oracletoDataTable(strScript, doReturnData);
I am also not sure this is set up to produce the correct results. Can you please advise where i am going wrong here?
I actually found a more efficient approach to this solution thanks to codeproject.com.
This is my final method that is working great. All i do is call it with my schema.table and datatable and it handles the rest:
public static void WriteToServer(string qualifiedTableName, DataTable dataTable)
{
//**************************************************************************************************************************
// Summary: Hit the Oracle DB with the provided datatable. bulk insert data to table.
//**************************************************************************************************************************
// History:
// 10/03/2017 Created
//**************************************************************************************************************************
try
{
OracleConnection oracleConnection = new OracleConnection(Variables.strOracleCS);
oracleConnection.Open();
using (OracleBulkCopy bulkCopy = new OracleBulkCopy(oracleConnection))
{
bulkCopy.DestinationTableName = qualifiedTableName;
bulkCopy.WriteToServer(dataTable);
}
oracleConnection.Close();
oracleConnection.Dispose();
}
catch (Exception ex)
{
Utility.db.Log.Write(Utility.db.Log.Level.Error, "Utility", "db:WriteToServer: " + ex.Message);
throw;
}
}
ref: https://www.codeproject.com/Questions/228101/oracle-data-bulk-insert
mycommand.ArrayBindCount = dtResults.Count;
mycommand.Parameters.Add(":parameterName", OracleDbType.Varchar2, dtResults.Select(c => c.ParameterName).ToArray(), ParameterDirection.Input);
mycommand.ExecuteNonQuery() ;
after CommandText set you may use the code above.
Related
I am trying to use Arraybinding to load multiple rows into a table. The approach works for inline queries but not when done via Stored Procedure.
I am expecting that an exception is raised with inner Errors object populated with row numbers where it failed.
This is an example from Oracle site and it works perfectly fine for me. But as soon as i replace the inline query with a stored procedure, it fails with single error and doesn't contain any information for the row which failed.
https://docs.oracle.com/html/B14164_01/featOraCommand.htm#i1007888
/* Database Setup
drop table depttest;
create table depttest(deptno number(2));
*/
This is the program
using System;
using System.Data;
using Oracle.DataAccess.Client;
class ArrayBindExceptionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle;";
con.Open();
OracleCommand cmd = new OracleCommand();
// Start a transaction
OracleTransaction txn = con.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
int[] myArrayDeptNo = new int[3] { 10, 200000, 30 };
// int[] myArrayDeptNo = new int[3]{ 10,20,30};
// Set the command text on an OracleCommand object
cmd.CommandText = "insert into depttest(deptno) values (:deptno)";
cmd.Connection = con;
// Set the ArrayBindCount to indicate the number of values
cmd.ArrayBindCount = 3;
// Create a parameter for the array operations
OracleParameter prm = new OracleParameter("deptno", OracleDbType.Int32);
prm.Direction = ParameterDirection.Input;
prm.Value = myArrayDeptNo;
// Add the parameter to the parameter collection
cmd.Parameters.Add(prm);
// Execute the command
cmd.ExecuteNonQuery();
}
catch (OracleException e)
{
Console.WriteLine("OracleException {0} occured", e.Message);
if (e.Number == 24381)
for (int i = 0; i < e.Errors.Count; i++)
Console.WriteLine("Array Bind Error {0} occured at Row Number {1}",
e.Errors[i].Message, e.Errors[i].ArrayBindIndex);
txn.Commit();
}
cmd.Parameters.Clear();
cmd.CommandText = "select count(*) from depttest";
decimal rows = (decimal)cmd.ExecuteScalar();
Console.WriteLine("{0} row have been inserted", rows);
con.Close();
con.Dispose();
}
}
Replace the code with stored procedure
cmd.CommandText = "SPName";
cmd.CommandType = CommandType.StoredProcedure;
Stored Procedure
PROCEDURE trial (p_deptno IN number)
AS
BEGIN
insert into ses.depttest(deptno) values (P_deptno);
END trial;
I'm writing a windows form that populates a DataTable and I want it to insert into an Oracle Table. I've seen some examples here that use the OracleDataAdapter to do this so I don't have to loop through all the records. The code doesn't have any errors but when I check the Table using Toad(I did refresh) I don't see it. I used the example below
Update and insert records into Oracle table using OracleDataAdapter from DataTable
Here is how my DataTable is made:
public DataTable dtMain = new DataTable();
public void FillTable(DataTable dt)
{
dtMain.Columns.Add("SERIAL", typeof(System.String));
dtMain.Columns.Add("LOCATION", typeof(System.String));
dtMain.Columns.Add("UPC", typeof(System.String));
dtMain.Columns.Add("PRODUCT", typeof(System.String));
dtMain.Columns.Add("CREATED_BY", typeof(System.String));
dtMain.Columns.Add("CREATED_DATE", typeof(System.DateTime));
dtMain.Columns.Add("SKU", typeof(System.String));
dtMain.Columns.Add("MAN_DATE", typeof(System.DateTime));
dtUpload.Columns[0].Unique = true;
dtMain.Merge(dt);
}
This is the how I'm trying to insert into the database
private void btnUpload_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strSelect = "SELECT serial, upc, man_date, location, product, created_by, created_date, serial from schema.table where rownum < 2";
string strInsert = "INSERT INTO schema.table (serial, upc, man_date, location, product, created_by, created_date, serial) VALUES (:serial, :upc, :man_date, :location, :product, :created_by, :created_date, :serial)";
string conStr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
OracleConnection connection = new OracleConnection(conStr);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
OracleDataAdapter adapterS = new OracleDataAdapter();
adapterS.SelectCommand = new OracleCommand(strSelect, connection);
adapterS.Fill(dt);
dt.Rows.Remove(dt.Rows[0]);
dt.Merge(dtUpload);
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
for (int i = 0; dt.Rows.Count > i; i++)
{
OracleDataAdapter adapter = new OracleDataAdapter();
adapter.InsertCommand = new OracleCommand(strInsert, connection);
adapter.InsertCommand.BindByName = true;
OracleParameter pSerial = new OracleParameter(":serial", OracleDbType.Varchar2);
pSerial.SourceColumn = dt.Columns[0].ColumnName;
pSerial.Value = dtUpload.Rows[i][0];
OracleParameter pLocation = new OracleParameter(":location", OracleDbType.Varchar2);
pLocation.SourceColumn = dt.Columns[1].ColumnName;
pLocation.Value = dtUpload.Rows[i][1];
OracleParameter pUPC = new OracleParameter(":upc", OracleDbType.Date);
pUPC.SourceColumn = dt.Columns[2].ColumnName;
pUPC.Value = dtUpload.Rows[i][2];
OracleParameter pProduct = new OracleParameter(":product", OracleDbType.Varchar2);
pProduct.SourceColumn = dt.Columns[3].ColumnName;
pProduct.Value = dtUpload.Rows[i][3];
OracleParameter pCreatedBy = new OracleParameter(":created_by", OracleDbType.Varchar2);
pCreatedBy.SourceColumn = dt.Columns[4].ColumnName;
pCreatedBy.Value = dtUpload.Rows[i][4];
OracleParameter pCreatedDate = new OracleParameter(":created_date", OracleDbType.Varchar2);
pCreatedDate.SourceColumn = dt.Columns[5].ColumnName;
pCreatedDate.Value = dtUpload.Rows[i][5];
OracleParameter pSKU = new OracleParameter(":SKU", OracleDbType.Date);
pSKU.SourceColumn = dt.Columns[6].ColumnName;
pSKU.Value = dtUpload.Rows[i][6];
OracleParameter pManDate = new OracleParameter(":man_date", OracleDbType.Varchar2);
pManDate.SourceColumn = dt.Columns[7].ColumnName;
pManDate.Value = dtUpload.Rows[i][7];
adapter.InsertCommand.Parameters.Add(pSerial);
adapter.InsertCommand.Parameters.Add(pLocation);
adapter.InsertCommand.Parameters.Add(pUPC);
adapter.InsertCommand.Parameters.Add(pProduct);
adapter.InsertCommand.Parameters.Add(pCreatedBy);
adapter.InsertCommand.Parameters.Add(pCreatedDate);
adapter.InsertCommand.Parameters.Add(pserial);
adapter.InsertCommand.Parameters.Add(pManDate);
}
try
{
adapter.Update(dt);
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
connection.Close();
connection.Dispose();
}
If someone can give me some pointers that would be great, I've been Googling for 2 days and I just can't figure it out. I bet it's something simple
Update:
Thank you for the reply, it took me a bit to get back to this project. When I posted this I didn't realize I forgot to include my select statement.
For the OracleParameter value, I thought using SourceColumn would use that column for the values.
I did update the DataTable with the serial being unique. It still doesn't insert the data. If I included the Parameter.value would I have loop row by row to do this? Above I corrected/updated it with the current code.
Second Update:
Ok, I tried looping through the parameters to add the values from the DataTable, no errors but still not inserting in the database. I know my connectionstring is correct because the select query works. The code above has been updated for the changes I made. If some Oracle guru can shed some light on my problem a virtual high-five is waiting for them.
I never used OracleDataAdapter but I see these possible issues:
I don't think you can use OracleDataAdapter straight away, first you have to select an existing table from Oracle and based on this result you can do Update/Insert/Delete on it. Where is your strSelect string? I don't see it.
You created all the OracleParameter but I don't see that you assign any value to it, they are all empty. I would expect something like pOptoroLP.Value = ...; before you make any insert.
You should define a unique, resp. Primary Key column like dt.Columns["SERIAL"].Unique = true; in order to make Update() or Delete(). Maybe it is not required for Insert(), I don't know.
Did you follow the examples in Data Provider for .NET Developer's Guide
I finally found the problem, the row state in the DataTable needs to in the state of Added for it to work. If someone else has this problem here is my new code and you can compare it to what I was trying to do. Thank you Wernfried Domscheit for the Oracle part but it turned out to be my DataTable was the issue though setting the Unique column was probably an issue as well, I didn't check. The OracleCommandBuilder took care of the insert statements and parameters for me.
private void btnUpload_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strSelect = "SELECT serial, upc, man_date, location, product, created_by, created_date, serial from schema.table where rownum < 2";
string strInsert = "INSERT INTO schema.table (serial, upc, man_date, location, product, created_by, created_date, serial) VALUES (:serial, :upc, :man_date, :location, :product, :created_by, :created_date, :serial)";
string conStr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
OracleConnection connection = new OracleConnection(conStr);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
OracleDataAdapter adapter = new OracleDataAdapter(strSelect, conStr);
OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
adapter.Fill(dt);
dt.Columns["SERIAL"].Unique = true;
dt.Merge(dtUpload);
dt.Rows.Remove(dt.Rows[0]);
foreach (DataRow row in dt.Rows)
{
row.SetAdded();
}
try
{
adapter.Update(dt);
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
finally
{
connection.Close();
connection.Dispose();
}
}
All my data table column fields from the stored procedure is string fields as like given below
[Account Code] varchar(10),
Filler1 varchar(5),
[Accounting Period] varchar(7),
[Transaction Date] varchar(8),
Filler2 varchar(2),
[Record Type] varchar(1),
[Source] varchar(2),
[Journal No] varchar(5),
[Journal Line] varchar(7)
Using the below code only I am picking the value from the SP to the dataset as given below
public DataSet InvoicesToSageExtractGoodsIn(string invoiceDateFrom)
{
SqlConnection conn = null;
DALFactory dalFactory = null;
SqlDataAdapter da = null;
try
{
DataSet dsInvoiceCustomer = new DataSet();
dalFactory = new DALFactory();
conn = new SqlConnection(dalFactory.ConnectionStringVI);
conn.Open();
SqlCommand sqlCommand = new SqlCommand("prc_ReturnSageExtractGoodsIn", conn);
sqlCommand.CommandType = CommandType.StoredProcedure;
DALSystemTable dst = new DALSystemTable(this.dao);
sqlCommand.CommandTimeout = Convert.ToInt32(dst.GetSystemConstant("CommandTimeOut"));
SqlParameter param1 = sqlCommand.Parameters.Add("#InvoiceDateFrom", SqlDbType.DateTime);//VI-165
param1.Direction = ParameterDirection.Input;
param1.Value = invoiceDateFrom;
DataSet dsInvoice = new DataSet("VisionInvoicing");
DataTable dtInvoiceNos = new DataTable("tblSageExtractGoodsIn");
da = new SqlDataAdapter(sqlCommand);
da.Fill(dsInvoice);
dsInvoice.Tables[0].TableName = "tblGenerateInvoice";
return dsInvoice;
}
catch (Exception ex)
{
throw new DatabaseException(ex.Message, ex);
}
}
When I try to pick the MaxLength of the column (dtSAGEExtract.Columns[i].MaxLength) from that dataset table it always shows -1 value.
foreach (DataRow drExtract in dtSAGEExtract.Rows)
{
int fieldCount = (dtSAGEExtract.Columns.Count);
for (int i = 0; i < fieldCount; i++)
{
int length = dtSAGEExtract.Columns[i].MaxLength;
writer.Write(drExtract[i].ToString().PadRight(length));
}
writer.WriteLine();
}
writer.Close();
Does anyone have any idea why it is always showing -1 for all the fields?
First you need to add your DataTable to the DataSet to make it work after you created the DataTable because they are not connected in your example and filling the DataSource has no impact on the DataTable created in the next line so that you can use the additional schema information:
dsInvoice.Tables.Add(dtInvoiceNos);
then you need to call the SqlDataAdapter.FillSchema Method on your SqlDataAdapter to get more information from your database then just the data when using only the Fill method
da.FillSchema(dtInvoiceNos, SchemaType.Source);
da.Fill(dsInvoice);
The fill operations must be called after you added the table to the dataset.
It does not represent the MaxLength of DataTable column. It is not depend on database schema either.
It return -1 because it is default value when you do not set anything.
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.maxlength(v=vs.110).aspx
Because you not fill schema to dataset.
Normaly -1 is default length of column.
You should use:
da.FillSchema(dsInvoice, SchemaType.Mapped)
UPDATE:
DataTable dtInvoiceNos = dsInvoice.Tables[0];
Please check: http://msdn.microsoft.com/en-us/library/229sz0y5(v=vs.110).aspx
I've data in DataTable with 2 rows and 3 columns. I want to insert that data into Oracle table.
How can I insert? please give me with some example.
And also
How can I pass datatable to storedprocedure in ORACLE...
I pass datatable in below mensioned manner, but datatable type problem is comming. how can I solve this?
cmd.Parameters.Add("#Details",dtSupplier);
(OR)
cmd.Parameters.Add("Details", DbType.Single).Value = dtSupplier.ToString();
want to insert dataset or a datatable into ORACLE,
create an ORACLE data adapter.
create a command object for insertion,
set the CommandType to StoredProcedure.
Update command of the data adapter,
pass the dataset or datatable as parameter.
like this:
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmdOra = new OracleCommand(StoredProcedureName, Connection);
cmdOra.CommandType = CommandType.StoredProcedure;
da.InsertCommand = cmdOra;
da.Update(dsDataSet);
OR
if above dont work than pass datatable as xml prameter than than process it
For details check : ADO.NET DataTable as XML parameter to an Oracle/SQL Server Database Stored Procedure
OR
Check this thread on Oracle site : Thread: Pass data table to Oracle stored procedure
Check existing answer : How to Pass datatable as input to procedure in C#?
I'm very late for this answer, but I elaborated a bit to have some more readable (I hope) code, and to avoid all those .ToString() for the values so nulls and other less common values can be handled; here it is:
public void Copy(String tableName, DataTable dataTable)
{
var insert = $"insert into {tableName} ({GetColumnNames(dataTable)}) values ({GetParamPlaceholders(dataTable)})";
using (var connection = /*a method to get a new open connection*/)
{
for (var row = 0; row < dataTable.Rows.Count; row++)
{
InsertRow(dataTable, insert, connection, row);
}
}
}
private static void InsertRow(DataTable dataTable, String insert, OracleConnection connection, Int32 row)
{
using (var command = new OracleCommand(insert, connection))
{
AssembleParameters(dataTable, command, row);
command.ExecuteNonQuery();
}
}
private static void AssembleParameters(DataTable dataTable, OracleCommand command, Int32 row)
{
for (var col = 0; col < dataTable.Columns.Count; col++)
{
command.Parameters.Add(ParameterFor(dataTable, row, col));
}
}
private static OracleParameter ParameterFor(DataTable dataTable, Int32 row, Int32 col)
{
return new OracleParameter(GetParamName(dataTable.Columns[col]), dataTable.Rows[row].ItemArray.GetValue(col));
}
private static String GetColumnNames(DataTable data) => (from DataColumn column in data.Columns select column.ColumnName).StringJoin(", ");
private static String GetParamPlaceholders(DataTable data) => (from DataColumn column in data.Columns select GetParamName(column)).StringJoin(", ");
private static String GetParamName(DataColumn column) => $":{column.ColumnName}_param";
Hope this can be still useful to somebody
The best idea would be follow the step mentioned below
Create a transaction
Begin the transaction
Loop through you data table
call your procedure
If no error occurred commit transaction
else roll back transaction
Regarding this part of your question:
cmd.Parameters.Add("#Details",dtSupplier);
(OR)
cmd.Parameters.Add("Details", DbType.Single).Value = dtSupplier.ToString();
What is the type of the "Details" parameter? Is it a Single? Then you would have to pick one (1) value from your DataTable and pass it to your parameter, something like dtSupplier.Rows[0]["col"].
If you use dtSupplier.ToString() you are just making a string of the entire DataTable (which i guess will always be the type name of DataTable).
First of all, you need to add Oracle.DataAccess.dll as reference in Visual Studio. In most cases, you can find this dll in the directory C:\ProgramData\Oracle11g\product\11.2.0\client_1\ODP.NET\bin\2.x\Oracle.DataAccess.dll
If just you need to insert the records from DataTable to Oracle table, then you can call the below function. Consider that your DataTable name is dt.
string error = "";
int noOfInserts = DataTableToTable(dt,out error);
1. Without using Oracle Parameters(special character non-safe)
The definition of the function is given below. Here, we are just making the query dynamic for passing this as a sql statement to the InsertWithQuery function.
public int DataTableToTable(DataTable dt,out string error)
{
error = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
finalSql = "INSERT INTO TABLENAME SELECT ";
for (int j = 0; j < dt.Columns.Count; j++)
{
colValue += "'" + dt.Rows[i][j].ToString() + "',";
}
colValue = colValue.Remove(colValue.Length - 1, 1);
finalSql += colValue + " FROM DUAL";
InsertWithQuery(finalSql, out error);
if (error != "")
return error;
inserts++;
colValue = "";
}
}
The code for InsertWithQuery function is given below. Here, in the connection string you have to place you database details like Host,Username,Password etc.
public int InsertWithQuery(string query, out string error)
{
error = "";
int rowsInserted = 0;
if (error == "")
{
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=)));User Id=;Password=");
OracleTransaction trans = con.BeginTransaction();
try
{
error = "";
OracleCommand cmd = new OracleCommand();
cmd.Transaction = trans;
cmd.Connection = con;
cmd.CommandText = query;
rowsInserted = cmd.ExecuteNonQuery();
trans.Commit();
con.Dispose();
return rowsInserted;
}
catch (Exception ex)
{
trans.Rollback();
error = ex.Message;
rowsInserted = 0;
}
finally
{
con.Dispose();
}
}
return rowsInserted;
}
2. With using Oracle Parameters(special character safe)
This can handle special characters like single quotes like scenarios in the column values.
public int DataTableToTable(DataTable dt,out string error)
{
error = "";
string finalSql = "";
List<string> colValue = new List<string>();
List<string> cols = new List<string>() {"COLUMN1","COLUMN2","COLUMN3"};
for (int i = 0; i < dt.Rows.Count; i++)
{
finalSql = "INSERT INTO TABLENAME(COLUMN1,COLUMN2,COLUMN3) VALUES(:COLUMN1,:COLUMN2,:COLUMN3) ";
for (int j = 0; j < dt.Columns.Count; j++)
{
colValue.Add(dt.Rows[i][j].ToString());
}
objDAL.InsertWithParams(finalSql,colValue,cols, out error);
if (error != "")
return error;
inserts++;
colValue.Clear();
}
}
And the InsertWithParams is given below
public string InsertWithParams(string sql, List<string> colValue, List<string> cols, out string error)
{
error = "";
try
{
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=)));User Id=;Password=");
OracleCommand command = new OracleCommand(sql, con);
for (int i = 0; i < colValue.Count; i++)
{
command.Parameters.Add(new OracleParameter(cols[i], colValue[i]));
}
command.ExecuteNonQuery();
command.Connection.Close();
}
catch (Exception ex)
{
error = ex.Message;
}
return null;
}
try {
//Suppose you have DataTable dt
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source='Give path of your access database file here';Persist Security Info=False";
OleDbConnection dbConn = new OleDbConnection(connectionString);
dbConn.Open();
using (dbConn)
{
int j = 0;
for (int i = 0; i < 2; i++)
{
OleDbCommand cmd = new OleDbCommand(
"INSERT INTO Participant_Profile ([column1], [column2] , [column3] ) VALUES (#c1 , #c2 , #c3 )", dbConn);
cmd.Parameters.AddWithValue("#c1", dt.rows[i][j].ToString());
cmd.Parameters.AddWithValue("#c2", dt.rows[i][j].ToString());
cmd.Parameters.AddWithValue("#c3", dt.rows[i][j].ToString());
cmd.ExecuteNonQuery();
j++;
}
}
}
catch (OleDbException exception)
{
Console.WriteLine("SQL Error occured: " + exception);
}
I know it's been a big WHILE upon the matter, but the same need: "to insert data from a datatable to an Oracle table" has happened to me. I found this thread. I also tried the answers and came to the conclusion that executing a
...
cmd.ExecuteNonQuery();
...
in a loop, is bad. Reeaaally bad. The first thing that is bad is performance, the second is unnecessary complexity, the third is unnecessary Oracle Objects (stored proc). The time it takes to complete, lets say 200 rows, is almost 1 minute and that's me rounding it down. So in the hope that someone else will find this helpful here's my experience.
I got stubborn and searched some more, so I found out this, true it's from 2018. But I'm in 2021 myself...
So the base code is:
using Oracle.ManagedDataAccess.Client; // you don't need other dll, just install this from nuget gallery
using System.Data;
public static void Datatable2Oracle(string tableName, DataTable dataTable)
{
string connString = "connection string";
OracleBulkCopy copy= new(connString, OracleBulkCopyOptions.UseInternalTransaction /*I don't know what this option does*/);
copy.DestinationTableName = tableName;
copy.WriteToServer(dataTable);
copy.Dispose();
}
This should match a raw oracle DDL performance:
create table table_name as select * from other_table_name
I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....
In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;
It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0
I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}