I had search in the internet and not much info I can get. I try to insert data to table database oracle, but it's not working when I use OracleConnection and OracleTransaction to commit and rollback. the following code ;
using (Entities dbContext = new Entities())
{
string constr = "data source=10.10.10.228:1521/MPMBO;password=tax;user id=TAX";
using (OracleConnection orcConnect = new OracleConnection(constr))
{
orcConnect.Open();
OracleCommand orcCommand = orcConnect.CreateCommand();
OracleTransaction orcTransaction;
orcTransaction = orcConnect.BeginTransaction(IsolationLevel.ReadCommitted);
orcCommand.Transaction = orcTransaction;
try
{
MPMISTAX_HDRMASUK item = new MPMISTAX_HDRMASUK();
//something item to include...
dbContext.MPMISTAX_HDRMASUK.Add(item);
dbContext.SaveChanges();
for (int j = 0; j < Id.Length; j++)
{
MPMISTAX_DTLMASUK itemA = new MPMISTAX_DTLMASUK();
//something code
dbContext.MPMISTAX_DTLMASUK.Add(itemA);
}
dbContext.SaveChanges();
orcTransaction.Commit();
}
catch (Exception dbEx)
{
orcTransaction.Rollback();
throw new Exception(dbEx.Message);
}
}}
I can't get error, but the table not insert in database oracle. I hope you can help my problem. Thank you
Related
Haha.. i don't know how to delete data based on selected row in radgridview and also delete it in mysql. this is going to be a confusing school assignment, does anyone know how to solve it?
this is the line of code i made:
private void A_3_BtnDelete_Click_1(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["GreatRetail_connect"].ConnectionString;
string query = "DELETE FROM tb_stock_product WHERE ID_product= ID_product ";
MySqlConnection conn = new MySqlConnection(mainconn);
for (int i = 0; i < RAD_GridView_ShowData.SelectedRows.Count - 1; i++)
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("ID_product", RAD_GridView_ShowData.SelectedRows[i].Cells[0].Value.ToString());
MySqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
MessageBox.Show("Delete data sucsessfully");
conn.Close();
ShowData();
}
}
it would be great today if anyone would like to help.
I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?
public class AndroidSQLiteDb : ISQLiteDB
{
public SQLiteAsyncConnection GetConnection()
{
var dbFileName = "backend.db3";
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, dbFileName);
return new SQLiteAsyncConnection(path);
}
}
public async void FirstSyncContacts(string host, string database, string contact)
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var sql = "SELECT * FROM tblContacts WHERE Coordinator = '" + contact + "'";
var getContacts = conn.QueryAsync<ContactsTable>(sql);
var resultCount = getContacts.Result.Count;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:00");
//Check if the retailer has been sync
if (resultCount < 1)
{
try
{
syncStatus.Text = "Syncing Retailer";
var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=9DpndD";
string contentType = "application/json";
JObject json = new JObject
{
{ "ContactID", contact }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (content != "")
{
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
}
await conn.InsertAsync(contactsresult);
}
}
//Proceed to next function
FirstSyncRetailerGroup(host, database, contact);
}
catch (Exception ex)
{
Console.Write("Syncing Retailer Error " + ex.Message);
}
}
//If not get the retailer
else
{
SyncContacts(host, database, contact);
}
}
catch (Exception ex)
{
Console.Write("Syncing Retailer Error " + ex.Message);
}
}
Use the non-async Insert in one background thread, instead of 3000 separate async calls...
Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.
No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.
Example using SQLiteConnection:
// Use the non-async version of SQLiteConnection
var conn = new SQLiteConnection(dbPath, true, null);
// code removed for example...
await System.Threading.Tasks.Task.Run(() =>
{
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
// start a transaction block so all 3000 records are committed at once.
conn.BeginTransaction();
// Use `foreach` in order shortcut the need to retrieve the object from the list via its index
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
conn.Insert(item);
}
conn.Commit();
});
Example using SQLiteAsyncConnection:
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
~~~
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
}
conn.InsertAsync(contactsresult); // Insert the entire list at once...
I had the same problem so even the answer is some years late, maybe can be usefull for somebody.
This is how I did.
First: I get the data all from server as json
var response = await client.GetAsync("your_server_url");
var content = await response.Content.ReadAsStringAsync();
ResponseData = JsonConvert.DeserializeObject<DataModel>(content);
Second: Save data to database
await conn.InsertAllAsync(ResponseData)
But in my case, because our app works offline data, I first insert all data in a temp table, then I get all new records comparing main table with temp table.
NewDataFromTemp = await conn.QueryAsync<DataModel>("SELECT * FROM [TableTemp] t WHERE t.[TABLE_ID] NOT IN (SELECT g.[TABLE_ID] FROM [MainTable] g)");
And insert new records in Main table
await conn.InsertAllAsync(NewDataFromTemp)
Then I check for updated records
UpdatedDataFromTemp = await conn.QueryAsync<DataModel>("SELECT t.* FROM [TableTemp] t, [MainTable] o WHERE t.[TABLE_ID]=o.[TABLE_ID] AND t.[TABLE_UPDATED]>o.[TABLE_UPDATED]");
And update all record in main table
await conn.UpdateAllAsync(UpdatedDataFromTemp);
I use logical delete so when updating the logical delete will be updated too.
I'm sort of having a hard time with this one. Well ok, I have two different solutions (solution1 has a WebApplication Project; solution2 has a Website Project). Inside the two solutions, there's a WCF service structure. I have the exact same code in both services (in their respective solutions). My code compiles just fine. From the service I do a simple call to a procedure that returns a cursor. When I execute the service from the WebApplication it works just fine; when I do the same from the Website I get error: "wrong number or types of arguments". They both call the same procedure, in the same DB. And I triple check my code, and is the same in both services. Any ideas or suggestions? My code is as follows in both solutions:
Service.cs
public List<A1001310> SearchClient_A1001310()
{
DataTable dataTable = new DataTable();
dataTable = DataManager.SearchClient();
List<A1001310> list = new List<A1001310>();
list = (from DataRow dr in dataTable.Rows
select new A1001310()
{
Id = Convert.ToInt32(dr["CLIENT_ID"]),
//ClientName = dr["NOM_CLIENTE"].ToString()
}).ToList();
return list;
}
DataManager.cs
public static DataTable SearchClient()
{
try
{
using (OleDbCommand cmd = new OleDbCommand(packetName + ".select_A1001310"))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlManager sqlManager = new SqlManager();
return sqlManager.GetDataTable(cmd);
}
}
catch (Exception ex)
{
//TODO; Handle exception
}
return null;
}
The call to DataTable is:
public DataTable GetDataTable(OleDbCommand cmd)
{
using (DataSet ds = GetDataSet(cmd))
{
return ((ds != null && ds.Tables.Count > 0) ? ds.Tables[0] : null);
}
}
public DataSet GetDataSet(OleDbCommand cmd)
{
using (DataSet ds = new DataSet())
{
this.ConvertToNullBlankParameters(cmd);
using (OleDbConnection conn = new OleDbConnection(cmd.Connection == null ? _dbConnection : cmd.Connection.ConnectionString))
{
cmd.Connection = conn;
cmd.CommandTimeout = _connTimeout;
conn.Open();
//cmd.ExecuteScalar();
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
da.Fill(ds);
}
return ds;
}
}
The procedure is as follow:
PROCEDURE select_A1001310(io_cursor OUT lcursor_data)
AS
BEGIN
OPEN io_cursor FOR
--
SELECT client_id
FROM a1001310
WHERE status = 'A'
--
EXCEPTION
WHEN OTHERS THEN
IF io_cursor%ISOPEN THEN
CLOSE io_cursor;
END IF;
--REVIRE: EXCEPTION HANDLER
END select_A1001310;
So if it helps anyone, I resolved my issue by specifying the OUT parameter declared in the procedure. This resulted in me changing from Oledb to OracleClient as follow:
public static DataTable SearchClient()
{
string connection = ConfigurationManager.ConnectionStrings["DBConnection_Oracle"].ToString();
string procedure = packetName + ".p_search_client";
OracleParameter[] parameters = new OracleParameter[1];
parameters[0] = new OracleParameter("io_cursor", OracleType.Cursor, 4000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Current, String.Empty);
DataTable dt = new DataTable();
dt = DataManager_Oracle.GetDataTable_(connection, procedure, parameters);
return dt;
}
It seems that on the Website environment it didn't like leaving out the OUT parameter; whereas on the WebApplication I did not specify it, and it worked just fine... If some one know the why , PLEASE let me know :)
I try to fill my dataset with multiple tables using stored procedure on SQLServer. Code is simple:
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(myDataSet);
}
}
}
But somehow Fill only creates (and fills) first table (not the others). It is not about procedure because it returns normal data. Am I missing something in the adapter?
I still don't know why Fill is not working. It worked before. There's walkaround (without need to specificate your datatables) but it envolves SqlDataReader
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
conn.Open();
using (var reader = new command.ExecuteReader())
{
while(!reader.IsClosed) //table.Load closes reader if it contains no more rows
{
var table = new DataTable();
myDataset.Tables.Add(table);
table.Load(reader)
}
}
}
}
I am inserting values in to Database from a Webform using ADO.NET, C#. DB I am using is Oracle Database. Values are not being inserted and the program gets struck at the cmd.ExecuteNonquery()
Here is my Code below, Please let me know If I am doing any mistake.. I am using some Static Methods will that be any problem ?..
public Boolean AddDivCo(Int32 UserNo,String ID, String Role, String DivName )
{
Boolean ret = false;
OracleCommand cmd = new OracleCommand();
OracleConnection conn = new OracleConnection();
int i = 0;
try
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Conn_RIS"].ConnectionString;
conn.Open();
cmd.Connection = conn;
String mySQL = "INSERT INTO R4CAD_ADMIN (AdminUserNo, AdminID, AdminRole, AdminDivName)VALUES(:AdminUserNo,:AdminID,:AdminRole,:DivName)";
OracleParameter p1 = new OracleParameter("AdminUserNo", OracleType.Number);
p1.Value = UserNo;
cmd.Parameters.Add(p1);
OracleParameter p2 = new OracleParameter("AdminID", OracleType.VarChar);
p2.Value = ID;
cmd.Parameters.Add(p2);
OracleParameter p3 = new OracleParameter("AdminRole", OracleType.VarChar);
p3.Value = Role;
cmd.Parameters.Add(p3);
OracleParameter p4 = new OracleParameter("DivName", OracleType.VarChar);
p4.Value = DivName;
cmd.Parameters.Add(p4);
cmd.CommandText = mySQL;
i = cmd.ExecuteNonQuery();
if (i != 0)
{
ret = true;
}
else
{
ret = false;
}
}
catch (Exception err)
{
Console.WriteLine(err.Message.ToString());
}
finally
{
cmd.Dispose();
//cmd = null;
//conn = null;
conn.Close();
}
return ret;
}
Is there a primary key defined on this table? If so, then my guess is that you have another session that already has inserted a record with this key, but has not yet terminated the transaction with a commit or rollback. I don't see a commit as part of your code - I assume you're doing that somewhere else?
Execute your code above once more, and while it's hung run the following query from another session:
SELECT
(SELECT username FROM v$session WHERE sid=a.sid) blocker,
a.sid,
' is blocking ',
(SELECT username FROM v$session WHERE sid=b.sid) blockee,
b.sid
FROM v$lock a JOIN v$lock b ON (a.id1 = b.id1 AND a.id2 = b.id2)
WHERE a.block = 1
AND b.request > 0;
This should tell you if you're being blocked by another session and what the SID is of that session.