I have an update statement that works fine when I run it from SQL Developer. However, when I try to run it in C#, the program will freeze on the line that executes the command and not output anything. I have it defined as follows below:
private static OracleCommand cmd = new OracleCommand();
private static OracleConnection conn = new OracleConnection();
conn.ConnectionString = Properties.Settings.Default.myconstring;
cmd.Connection = conn;
cmd.CommandText = "UPDATE mytable SET PARAM1 = :param1 WHERE PARAM2 = :param2";
cmd.CommandType = CommandType.Text;
cmd.BindByName = true;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":param1", OracleDbType.Single)).Value = param1Val;
cmd.Parameters.Add(new OracleParameter(":param2", OracleDbType.Int32)).Value = param2Val;
conn.Open();
try {
cmd.ExecuteNonQuery(); //Freezes here
} catch(Exception e) {
MessageBox.Show(e.ToString());
}
conn.Close();
I have verified my values being put in are correct.
Related
I connected my oracle database to visual studio and now I'm trying to execute procedure I created in my database.
I tried this:
OracleCommand cmd = new OracleCommand("BEGIN ADD_USER('"+txtName.Text+"','"+txtName2.Text+"',"+txtID.Text+"); END;" );
cmd.ExecuteNonQuery();
My procedure has 3 parameters : name, 2name, id. It works fine when I use this command in sqldeveloper, but I get error when I try it in my project.
using (OracleConnection cn = new OracleConnection("con string"))
{
cn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
cmd.Parameters.Add("YourSPParamName1", OracleDbType.{YourFieldTypeInDB}).Value = txtName.Text;
cmd.Parameters.Add("YourSPParamName2", OracleDbType.{YourFieldTypeInDB}).Value = txtName2.Text;
cmd.Parameters.Add("YourSPParamName3", OracleDbType.{YourFieldTypeInDB}).Value = txtID.Text;
cmd.ExecuteNonQuery();
}
Something like this should work.
Here's how It works for me:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "something";
sb.Password = "pass";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.Add("NAME", OracleDbType.Varchar2).Value = txtName.Text;
cmd.Parameters.Add("NAME2", OracleDbType.Varchar2).Value = txtName2.Text;
cmd.Parameters.Add("ID", OracleDbType.Int32).Value = txtID.Text;
cmd.ExecuteNonQuery();
If I calling a stored proc how do i detect that it has completed succesfully on the server as right now im just doing a try catch which is not the best way of doing this.
public bool deleteTeam(Guid teamId)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["uniteCms"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cs.ToString());
// the stored procedure
SqlCommand cmd = new SqlCommand(
"proc_unitecms_deleteTeam", myConnection);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#ID", teamId));
return true;
} catch(Exception ex)
{
return false;
}
}
You can return the affected rows number and return -1 in case of catch a exception .
You forget the ExecuteNonQuery.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
I'm a beginner and trying to create a simple program in C# for inserting and updating records in an Oracle database. I have managed to successfully connect to the database but I'm getting an exception for my SQL statement which states that (?) symbol is not supported. Why am I getting this exception and how can I fix this?
My code is:
private void btnSave_Click(object sender, EventArgs e)
{
OracleConnection con = null;
try
{
con = new OracleConnection();
string constr = "Data source=XE; User ID=cloudester; Password=cloudester123;";
if (con.State != ConnectionState.Open)
{
try
{
con.ConnectionString = constr;
con.Open();
//MessageBox.Show("Successfull connection");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught");
}
}
if (con.State == ConnectionState.Open)
{
string str = "Insert into EMP_DETAIL(EmpId, Name, Age)";
str += "values (?,?,?)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = Text;
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
}
}
catch { ... }
}
You need to use the named parameter for your command
string str = "Insert into EMP_DETAIL(EmpId, Name, Age) values (:EmpId, :Name, :Age)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = str; //cmd.CommandText = Text; not sure why did you use Text here
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
As agent5566 said, and from OracleCommand.Parameters property;
When using named parameters in an SQL statement called by an
OracleCommand of CommandType.Text, you must precede the parameter name
with a colon (:)
Use them like;
using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"Insert into EMP_DETAIL(EmpId, Name, Age)
values (:EmpId, :Name, :Age)";
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
con.Open();
cmd.ExecuteNonQuery();
}
By the way, System.Data.OracleClient has been marked as deprecated in .NET 4 version. You might wanna use Oracle Data Provider for .NET instead.
As an alternative, DataDirect and DevArt also have their own oracle providers for .NET.
public void CreateMySqlCommand()
{
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "SELECT * FROM Categories ORDER BY CategoryID";
myCommand.CommandTimeout = 15;
myCommand.CommandType = CommandType.Text;
}
Can I use Sql Server functions in myCommand.CommandText and why?
If you mean, SQL Server user defined functions. Then, yes; you can use it normally like:
myCommand.CommandText = "SELECT fn_Yourfunctionname(#parameternames)";
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add(new SqlParameter("#parameternames", ...
The reason it works is because this is the way that functions are called in SQL Server directly.
Another approach:
public T ExecuteScalarFunction<T>(string functionName, List<SqlParameter> parameters, SqlDbType returnSqlType) where T : new()
{
using (var conn = new SqlConnection(CTX.Database.GetDbConnection().ConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
using (var cmd = new SqlCommand(functionName, conn)) {
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
cmd.Parameters.Add("#RETURN_VALUE", returnSqlType).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
return (T)cmd.Parameters["#RETURN_VALUE"].Value;
}
}
}
i m making dll class for stored procedure as...help me to correct it...my boss said that i m missing parameter values to return but i m not getting anything to correct it...
public class transactionService
{
SqlConnection cs;
private void OpenConnection()
{
cs = new SqlConnection();
cs.ConnectionString = "Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True";
cs.Open();
}
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
cmd.Parameters.Add(new SqlParameter("member_id", SqlDbType.Int));
membership_details myObjec = new membership_details();
cmd.ExecuteNonQuery();
SqlDataReader sdr = cmd.ExecuteReader();
myObjec.fine_per_day = 0;
return myObjec;
help me to correct this code...i m trying to get fne_per_day as per member_id and after this reference is adding to return form in project from that according to member_id fine_per_day is calculated...as the creteria is like member_id=5,membership_desc=silver,gol,platinum,fineperday=30or 20or10
I think you will need something like this for returning the out parameter of your stored procedure:
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
cmd.Parameters.Add(new SqlParameter("#member_id", SqlDbType.Int));
//Sql parameter corresponding to the output parameter
cmd.Parameters.Add(new SqlParameter("#fine_per_day", SqlDbType.Int));
cmd.Parameters[cmd.Parameters.Count - 1].Direction = ParameterDirection.Output;
//execute the stored procedure
cmd.ExecuteNonQuery();
//obtain the value for the output parameter
myObjec.fine_per_day = (int)cmd.Parameters["#fine_per_day"].Value;
return myObjec;
}