Executing Oracle procedure - c#

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();

Related

C# Npgsql read cursor from procedure output parameter

I'm migration an application from a Oracle DB to a Postgres DB.
There are many procedures implemented that returns via output parameter a RefCursor. Just like this:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
OracleConnection conn = GetConnection(connStr);
OracleCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", OracleDbType.Varchar2, ParameterDirection.Input).Value = flowKey;
OracleParameter outCursor = cmd.Parameters.Add("p_cursor", OracleDbType.RefCursor, ParameterDirection.Output);
cmd.ExecuteNonQuery();
OracleRefCursor dataCursor = (OracleRefCursor)outCursor.Value;
OracleDataAdapter myAdapter = new OracleDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
Please notice thant I've to grab the parameter outCursor, cast as OracleRefCursor and set it to DataTable named "tableData" via DataAdapter.
To do the same but using Npgsql this is my approach:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", NpgsqlDbType.Varchar).Value = flowKey;
NpgsqlParameter outCursor = cmd.Parameters.Add(new NpgsqlParameter("p_cursor", NpgsqlDbType.Refcursor) { Direction = ParameterDirection.Output });
cmd.ExecuteNonQuery();
var dataCursor = (Refcursor)outCursor.Value;
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
But unfortunately seems that there is no equivalent in Npgsql for Refcursor
Any ideias how can I get arround this?
Thank you.
To everyone who needs to do the same, I recommend reading this: https://stackoverflow.com/a/47970680/2229993
Nonetheless this is how I solved this issue:
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = new NpgsqlCommand("CALL show_citiesProc('op');FETCH ALL IN \"op\";", conn);
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter(cmd);
myAdapter.Fill(tableData);
myAdapter.Dispose();

Converting SQL Server connection to Oracle database connection (ASP.NET Core MVC & C#)

I need a little help here. I'm trying to modify my functions in order to make them work in an Oracle database, I need to be able to get my Get and Create methods working on my Oracle database.
This is my create method:
public void CreateRow(Person person)
{
using SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SP_InserNewRow", con);
{
cmd.CommandType = CommandType.StoredProcedure;
}
cmd.Parameters.AddWithValue("#CODE", person.CODE);
cmd.Parameters.AddWithValue("#NAME", person.NAME);
cmd.Parameters.AddWithValue("#LASTNAME", person.LASTNAME);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
This is my get method:
public IEnumerable<Person>GetPersonList
{
var listPerson = new List<Person>;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select * from myview", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var person = new Person();
person.CODE = Convert.ToInt32(dr["CODE"].ToString());
person.NAME = dr["NAME"].ToString();
person.LASTNAME = dr["LASTNAME"].ToString();
listPerson.Add(person);
}
con.Close();
}
return listPerson;
}
Now, I am trying to connect the above methods to an Oracle database.
I added this:
using Oracle.DataAccess.Client
using Oracle.DataAccess
Changed my string connection to this:
"DATA SOURCE=10.204.3.1:1521/PROD;" + "PERSIST SECURITY INFO=True;USER ID=username; password=password; Pooling =False;"
I started modifying the Get method:
public IEnumerable<Person>GetPersonList
{
var listPerson = new List<Person>();
using (OracleConnection con = new OracleConnection(connectionString2))
{
OracleCommand cmd = new OracleCommand("select * from myview", con);
cmd.Connection = con;
cmd.InitialLOBFetchSize = 1000;
cmd.CommandType = CommandType.StoredProcedure;
var list = new listPerson();
list.CODE = Convert.ToInt32(dr["CODE"].ToString());
list.NAME = dr["NAME"].ToString();
list.LASTNAME = dr["LASTNAME"].ToString();
listPerson.Add(list);
}
con.Close();
}
return listPerson;
I am kinda lost, can help me to modify my methods?
EDIT:
readonly string connectionString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROD)));User Id=xxx;Password=xxxx;"
public IEnumerable<Person>GetPersonList
{
var listPerson = new List<Person>();
using (OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select * from myview", con);
cmd.Connection = con;
cmd.InitialLOBFetchSize = 1000;
cmd.CommandType = CommandType.Text;
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read()){
var list = new Person();
list.CODE = Convert.ToInt32(dr["CODE"].ToString());
list.NAME = dr["NAME"].ToString();
list.LASTNAME = dr["LASTNAME"].ToString();
listPerson.Add(list);
}
con.Close();
}
return listPerson;
}
My EDIT worked just fine. Thank you Steve :)

Issue in update statement

I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}

Inserting data to multiple table in my sqlworkbench

I'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Error while executing a sql command in c#

I am using asp.net with c# and there exist an error in these line of codes.
protected void btnsubmit_Click(object sender, EventArgs e)
{
string type = "c";
string FID = Session["FID"].ToString();
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
cn.ConnectionString = #"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
cmd.CommandText = "update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect("~/Faculty/Personaldet.aspx");
}
You haven't set the connection to the command
cmd.Connection = cn;
You need to assign the SqlConnection to the SqlCommand. As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception.
using (SqlConnection cn = new SqlConnection(#"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True")
{
cn.Open();
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
}
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();

Categories