OracleParameterCollection giving me weird errors - c#

Error CS1729 'OracleParameterCollection' does not contain a constructor that takes 0 arguments
My Code
OracleParameterCollection oracleParameter = new OracleParameterCollection(); <====== How do I create one?
oracleParameter.Add("User_Name", OracleDbType.Char).Value = UserName;
oracleParameter.Add("Entered_Password", OracleDbType.Char).Value = Password;
oracleParameter.Add("T1_Cursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
DataTable employeeDataTable = StoredProcedureCall.GenerateStoredProcedureCall(_connectionString, "GET_USER_INFO_BY_CREDENTIALS", oracleParameter, out temp);
Method in class
public DataTable GenerateStoredProcedureCall(String _connectionString, String StoredProcedure_Name, OracleParameterCollection ParameterNames, out String ResultFromDatabaseOperation)
{
DataTable dt = new DataTable();
try
{
using (OracleConnection cn = new OracleConnection(_connectionString))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = StoredProcedure_Name;
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add(ParameterNames);
da.SelectCommand = cmd;
da.Fill(dt);
ResultFromDatabaseOperation = "";
if (cmd.Parameters["RowCount"].Value != null)
{
ResultFromDatabaseOperation = cmd.Parameters["RowCount"].Value.ToString();
}
if (cmd.Parameters["RowCount"].Value == null)
{
ResultFromDatabaseOperation = "0";
}
return dt;
}
}
catch (OracleException ex)
{
ResultFromDatabaseOperation = "";
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine(ex.StackTrace.ToString());
return dt;
}
}

If StoredProcedureCall.GenerateStoredProcedureCall() is your own defined function, then You should not pass OracleParameterCollection list to it. You can create simple dictionary and pass to this function.
And then inside the function you can add parameter directly to command. i.e:
foreach(var i in params)
{
oraCommand.Parameters.Add(new OracleParameter(i.key, i.val));
}
There is no need to create new instance of OracleParameterCollection

Related

SqlDataAdapter filling with DataTable does not work

I have this code running in form_load event:
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("pp_sp_MachineAndOp", sqlConn);
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
sqlDa.Fill(sqlDt);
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
sqlDa.Dispose();
sqlConn.Close();
}
I get error 'Procedure or function 'pp_sp_MachineAndOp' expects parameter '#MachineAndOpID', which was not supplied.' at line:
sqlDa.Fill(sqlDt);
Important to say that if I open DataTable Visualizer of sqlDt at runtime I see expected results!
Here is a code behind Helper.ExecuteDataTable:
public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
What I am missing?
Remove everything except
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
your Helper.ExecuteDataTable is doing everything. you don't need to replicate same this in your code.
I think your helper class is creating connection with database as your data table has data.
So, try to remove stored proc name and connection object from adaptor and then check.
SqlDataAdapter sqlDa = new SqlDataAdapter();//use this only.
you can use below function(modification required as per your need):
public IDataReader ExecuteReader(string spName, object[] parameterValues)
{
command = GetCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
if (parameterValues != null)
{
for (int i = 0; i < parameterValues.Length; i++)
{
command.Parameters.Add(parameterValues[i]);
}
}
reader = command.ExecuteReader();
if (parameterValues != null)
command.Parameters.Clear();
return reader;
}

sqlcommand c# method with sql paramather

I have this method, which I have in the base class that helps me to select anything from the children classes and also to reduce code repetition. The problem is when I call it I get an error which is a NullReferenceException (and when I look it up I find that the command in the method is empty).
This is the method in question:
This way I already know how to use but the other one I don't
SqlCommand command = new SqlCommand("select * from Customers where idCustomer=#idCustomer", OpenConnection());
command.Parameters.AddWithValue("#idCustomer", Id);
SqlDataReader reader = command.ExecuteReader();
Customer Onecustomer = null;
if (reader.Read())
{
Onecustomer = ReadCustomer(reader);
}
protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
SqlCommand command = new SqlCommand();
DataTable dataTable;
DataSet dataSet = new DataSet();
try
{
command.Connection = OpenConnection();
command.CommandText = query;
command.Parameters.AddRange(sqlParameters);
command.ExecuteNonQuery();
adapter.SelectCommand = command;
adapter.Fill(dataSet);
dataTable = dataSet.Tables[0];
}
catch (SqlException e)
{
return null;
throw new Exception("Error :" + e.Message);
}
finally
{
CloseConnection();
}
return dataTable;
}
Here how I call it
string author = "Alfred Schmidt";
int id = 1;
// ExecuteEditQuery("UPDATE Books SET Title =#param1 WHERE idBook =#param2", sqlParameters);
//SqlParameter[] sqlParameters = new SqlParameter[1]
//{
// new SqlParameter ("#param1",author),
//};
SqlParameter[] myparm = new SqlParameter[1];
myparm[0] = new SqlParameter("#Author", SqlDbType.NVarChar, 200);
myparm[0].Value = author;
String query = #"SELECT * FROM Books WHERE Author =#Author";
DataTable dt = ExecuteSelectQuery(query, myparm);
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(dt.Rows.ToString());
}
Console.Write("");
1
Is your OpenConnection() method returns a connection object. It may couse the error, the implementation of the method is not given. Also the adpater is not defined in the code, may be it can be the cause of error too, if it is not initialized.
And i want to say few things about your code:
1) You have and unnecessary command.ExecuteNonQuery(); statement in your ExecuteSelectQuery method.
2) DataAdapter can directly fill DataTable, you dont have to use DataSet.
Here's a proper rewrite of your method.
protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
using (SqlCommand command = new SqlCommand())
try
{
command.CommandText = query;
command.Parameters.AddRange(sqlParameters);
command.Connection = OpenConnection();
DataTable dataTable = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
adapter.Fill(dataTable);
return dataTable;
}
catch (SqlException e)
{
return null;
throw new Exception("Error :" + e.Message);
}
finally
{
CloseConnection();
}
}
Note that the SqlDataAdapter can Open() and Close() the connection by itself, if the SqlConnection is Closed when Fill is called.

Add new parameters to exec procedure

I have a custom SQL exec to execute stored procedure and send DataTable and execute TableType in sql like:
//Execute
db.ExeSQLParam("usp_TaskStatus_Time_Calculation_Final", parameters, "#GuidIdTableType");
ExeSQLParam method:
public bool ExeSQLParam(string SprocName, DataTable paramArray, string tableTypeName)
{
var testc = new SqlParameter();
bool bFlag = false;
SqlCommand cmd = new SqlCommand(SprocName, this.dbconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(tableTypeName, SqlDbType.Structured));
cmd.Parameters[tableTypeName].Value = paramArray;
try
{
cmd.ExecuteNonQuery();
bFlag = true;
}
catch (SqlException e)
{
this.HandleSQLError(e, SprocName, paramArray.ToString());
}
finally
{
cmd.Dispose();
}
return bFlag;
}
My question is how can I add to this method another normal parameters , so I can execute as:
db.ExeSQLParam("usp_TaskStatus_Time_Calculation_Final", parameters, "#GuidIdTableType",
#anoteherParameter = 'valueanotherparameter', #other = 'valueoter');
How can I achieve that?
I try to change it to received output data as DataTable like:
public DataTable ExeSQLParamAndType(string SprocName, DataTable paramArray, string tableTypeName)
{
SqlCommand cmd = new SqlCommand(SprocName, this.dbconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(tableTypeName, SqlDbType.Structured));
cmd.Parameters[tableTypeName].Value = paramArray;
DataTable tbl = new DataTable("Table1")
{
Locale = System.Globalization.CultureInfo.InvariantCulture
};
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
da.Fill(tbl);
}
catch (SqlException e)
{
this.HandleSQLError(e, "GetTableBySQL", SprocName);
}
finally
{
cmd.Dispose();
}
return tbl;
}
but where I can add new parameters? with another parameters.Add? I'm a litte confused there
In C# you can provide optional parameters using the 'params' keyword, so you simply rewrite your method and supply the params parametres.

Error in SQL Server 2008

I have a table for user and my columns are User_Id, User_Pass, User_Type.
After I saved this table, I created a stored procedure and successfully ran a query. But after connecting from C#, I get an error:
Could not find stored procedure 'UserPassChek'
Data access code:
namespace Salse_Mangment_System.Dal
{
class DataAccessLayer
{
SqlConnection cn;
public DataAccessLayer()
{
cn = new SqlConnection(#"Data Source = DESKTOP-OH8J8IE; Initial Catalog = libarty_DB; Integrated Security = true");
}
// Method To Open cn
public void Open()
{
if(cn.State != ConnectionState.Open)
{
cn.Open();
}
}
// method To Close Cn
public void Close()
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
}
// method To read data from database
public DataTable selectdata (string store_prosudre , SqlParameter [] param)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = store_prosudre;
cmd.Connection = cn;
if (param != null)
{
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
// method to insert delete update data
public void Executecommand(string store_procdure , SqlParameter [] param)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType= CommandType.StoredProcedure;
cmd.CommandText = store_procdure;
cmd.Connection = cn;
if (param != null)
{
cmd.Parameters.AddRange(param);
}
cmd.ExecuteNonQuery();
}
}
}
and class logincls is
class Logincls
{
// make function to cheek login procedure
public DataTable login(string ID,string Pwd)
{
Dal.DataAccessLayer dal = new Dal.DataAccessLayer();
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("#IDUser", SqlDbType.VarChar, 50);
param[0].Value = ID;
param[1] = new SqlParameter("#PasUser", SqlDbType.VarChar, 50);
param[1].Value = Pwd;
DataTable dt = new DataTable();
dal.Open();
dt = dal.selectdata("UserPassChek", param);
return dt;
}
}
Login form:
public class FrmLogin
{
Bl.Logincls log = new Bl.Logincls();
public FrmLogin()
{
InitializeComponent();
}
private void btnlog_Click(object sender, EventArgs e)
{
DataTable Dt = log.login(txtid.Text, txtpwd.Text);
if (Dt.Rows.Count>0)
{
MessageBox.Show(this, "تم الدخول", "دخول", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(this, "ليس لك الصلاحيات", "دخول", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btncan_Click(object sender, EventArgs e)
{
this.Close();
}
}
Try this again by adding schema name as below. dbo is the default schema and check your sp to find correct schema , that you have used.
dt = dal.selectdata("dbo.UserPassChek", param);

Must declare a scalar variable.?

I have to display bar chart using ajax extender tool. I have to display information on chart when I am selecting one value from drop down list. But it shows "Must declare a scalar variable" error. Please help me.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = string.Format("select Debit, Credit, Year From aTable where Name=#Name", ddlCountries.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} Order Distribution", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
In this line
string query = string.Format(#"select Debit, Credit, Year
From aTable where Name=#Name",
ddlCountries.SelectedItem.Value);
you have a parameter placeholder #Name but you don't add the required parameter to the SqlCommand that executes the sql. This produces the error that you see.
(By The way, string.Format requires the placeholder in the form {0}, but also if you fix that problem it is still wrong because you leave open the door to Sql Injection)
Fixing it requires a change in your GetData function.
You need to add an (optional) parameter array as another argument
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if(prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
And now, when you call that method, you could write
string query = "select Debit, Credit, [Year] From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#Name", SqlDbType.NVarChar).Value =
ddlCountries.SelectedItem.Value.ToString());
DataTable dt = GetData(query, prms);
Notice also that I have put the field Year between square brackets. Year is the name of a T-SQL Function and you should use this trick to avoid to confuse the SQL Parser

Categories

Resources