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.
Related
I am testing Oracle database. I wrote some code but my datareader has no rows, why? My "carros" table has data and I am selecting all of them but I am getting an empty result set it seems.
string constr = "Data Source=localhost:1521/XE;User Id=System;Password=password;";
OracleConnection con = new OracleConnection(constr);
OracleCommand oracleCommand = new OracleCommand();
oracleCommand.Connection = con;
oracleCommand.CommandText = "select preco from carro";
con.Open();
OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
string resultado = String.Empty;
//My test, I got hasRows as false
if (oracleDataReader.HasRows == false)
{
resultado = "no results";
}
//never enters this loop.
while (oracleDataReader.Read())
{
resultado += (string)oracleDataReader["preco"];
}
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
return resultado;
If HasRows is false after ExecuteReader, the problem is simply that the query is returning no rows so Read will return false as well. Perhaps the someValue variable is not set correctly.
From you description, it seems that your table is named carros while your query has used carro. Try to use
oracleCommand.CommandText = "select preco from carros";
A path towards solving this can include a scattering of logging commands that write to the file system.
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", "put error message here" + "\r\n");
Or for printing a variable:
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", ex.ToString() + "\r\n");
Pepper variations of this command throughout your script to see where failures are happening and to validate variable values.
Is it possible to correctly pass an OracleParameter to a boolean parameter in a pl/sql stored procedure?
I used the following workaround to bypass this limitation:
Wrap the function call using an anonymous block.
Return an output variable containing 1 or 0.
Read the output variable and cast it to boolean.
Here is some sample code:
using (var connection = new OracleConnection("<connection string>"))
{
var command = new OracleCommand();
command.Connection = connection;
command.CommandText =
"declare v_bool boolean;" +
"begin " +
"v_bool := auth_com.is_valid_username (:username); "+
"if (v_bool = TRUE) then select 1 into :v_result from dual; end if; " +
"if (v_bool = FALSE) then select 0 into :v_result from dual; end if; " +
"end;";
command.Parameters.Add(new OracleParameter { ParameterName = "username", OracleDbType = OracleDbType.NVarchar2, Size=512, Direction = ParameterDirection.Input });
command.Parameters.Add(new OracleParameter { ParameterName = "v_result", OracleDbType = OracleDbType.Decimal, Direction = ParameterDirection.Output });
try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
bool success = Convert.ToBoolean(((OracleDecimal)command.Parameters["v_result"].Value).ToInt32());
}
EDIT:
Alex Keh from Oracle, october 2013:
We're planning on supporting ODP.NET Boolean in the managed provider
in the near term, possibly in the middle of next year.
You can not use boolean parameters in SQL. So calling an stored procedure that takes or returns a boolean value won't work in SQL. There is no problem using such a procedure from within a pl/sql block.
ADDED from JCallico answer:
I used the following workaround to bypass this limitation:
Wrap the function call using an anonymous block.
Return an output variable containing 1 or 0.
Read the output variable and cast it to boolean.
Here is some sample code:
using (var connection = new OracleConnection("<connection string>"))
{
var command = new OracleCommand();
command.Connection = connection;
command.CommandText =
"declare v_bool boolean;" +
"begin " +
"v_bool := auth_com.is_valid_username (:username); "+
"if (v_bool = TRUE) then select 1 into :v_result from dual; end if; " +
"if (v_bool = FALSE) then select 0 into :v_result from dual; end if; " +
"end;";
command.Parameters.Add(new OracleParameter { ParameterName = "username", OracleDbType = OracleDbType.NVarchar2, Size=512, Direction = ParameterDirection.Input });
command.Parameters.Add(new OracleParameter { ParameterName = "v_result", OracleDbType = OracleDbType.Decimal, Direction = ParameterDirection.Output });
try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
bool success = Convert.ToBoolean(((OracleDecimal)command.Parameters["v_result"].Value).ToInt32());
}
EDIT:
Alex Keh from Oracle, october 2013:
We're planning on supporting ODP.NET Boolean in the managed provider
in the near term, possibly in the middle of next year.
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
I have something like this in my sql query
private static final String QUERY_PHYSICIAN_INFO= "SELECT * FROM PHYSICIAN_INFO WHERE ? = ?";
but following is not working..
Connection conn = null;
PreparedStatement stmt = null;
String logintype;
if(isInteger(id))
{
logintype="BADGEID";
}else{
logintype="ID";
}
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO);
stmt.setString(1, logintype);
stmt.setString(2, id);
ResultSet rs = stmt.executeQuery();
Physician phs = null;
Is there any special reason for this?
Thanks in advance.
? is for passing parameters, not field names.
If you must do this, build the SQL as
"SELECT * FROM PHYSICIAN_INFO WHERE " + "BADGEID" + " = ?"
You could try something like this because ? can be used only for passing parameters or you could use a database function and then pass values to the function.
private static final String QUERY_PHYSICIAN_INFO_BADGE= "SELECT * FROM PHYSICIAN_INFO WHERE BADGEID = ?";
private static final String QUERY_PHYSICIAN_INFO_ID= "SELECT * FROM PHYSICIAN_INFO WHERE ID = ?";
Connection conn = null;
PreparedStatement stmt = null;
String logintype;
if(isInteger(id))
{
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_BADGE);
}else{
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_ID);
}
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
Physician phs = null;
I have a stored procedure as
pr___GetArchiveData
Select * from TABLE1
SELECT * FROM TABLE2
SELECT * FROM TABLE 3
I want to get this result set into a dataset. Or access the values of three select queries!!
I have a DBML file in which when i drag and drop the stored procedure generates a code as follows:-
global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.pr___GetArchiveData")]
public ISingleResult<pr___GetArchiveDataResult> pr___GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(DbType="UniqueIdentifier")] System.Nullable<System.Guid> projectID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), projectID);
return ((ISingleResult<pr__Project_pr___GetArchiveData>)(result.ReturnValue));
}
In the code MVC3 Architecture + LINQ i have written a code to get the result set as follows :-
using (HBDataContext hb = new HBDataContext())
{
System.Data.DataSet ds = new System.Data.DataSet();
String connString = connString;
var conn = new System.Data.SqlClient.SqlConnection(connString);
var cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "pr__GetArchiveData";
cmd.Connection.Open();
var mReader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
//var reader = cmd.ExecuteReader();
//using (System.Data.SqlClient.SqlDataReader mReader = cmd.ExecuteReader())
//{
// while (mReader.Read())
//{
// mReader.Read();
var tbl1 = hb.Translate<tbl1 >(mReader).ToList();
// mReader = cmd.ExecuteReader();
mReader.NextResult();
var tbl2 = hb.Translate<tbl2 >(mReader).ToList();
mReader.NextResult();
var tbl3 = hb.Translate<tbl3>(mReader).ToList();
// }
// }
}
But while running it throws error as -
"Invalid attempt to call NextResult when reader is closed."
I am not sure where i am wrong!!
I have tried using it as while
(mReader.Read())
Kindly suggest!!!!
The code gen for ISingleResult won't provide multiple result sets
Try adding your own IMultipleResults wrapper - see the tutorial in http://blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql-and-multiple-result-sets-in-stored-procedures.aspx
In .dbml file for the stored procedure the code will be like
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.pr__Home_GetArchiveData")]
public ISingleResult<pr__Home_GetArchiveData> pr__Home_GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(Name="AlbumID", DbType="UniqueIdentifier")] System.Nullable<System.Guid> albumID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), albumID);
return ((ISingleResult<pr__Album_GetAlbumsFilesResult>)(result.ReturnValue));
}
Replace it with IMultipleResult as below `
[global::System.Data.Linq.Mapping.FunctionAttribute(Name = "dbo.pr__Home_GetArchiveData")]
[ResultType(typeof(tbl1))]
[ResultType(typeof(tbl2))]
[ResultType(typeof(tbl3))]
[ResultType(typeof(tbl4))]
public IMultipleResults pr__Home_GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "HOMEID", DbType = "UniqueIdentifier")] System.Nullable hOMEID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), hOMEID);
return ((IMultipleResults)result.ReturnValue);
}
in the code .
using (HBDataContext hb = new HBDataContext())
{
using (System.Data.Linq.IMultipleResults _results = hb.pr__Home_GetArchiveData(model.HomeID))
{
List<tbl1> _tbl1= _results.GetResult<tbl1>().ToList();
List<tbl2> _tbl2= _results.GetResult<tbl2>().ToList();
List<tbl3> _tbl3= _results.GetResult<tbl3>().ToList();
List<tbl4> _tbl4= _results.GetResult<tbl4>().ToList();}}
You will get the values of the Select queries from theStoredProcedure ...