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);
Related
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;
}
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
I have here stored procedure and I don't know how to bind to the datagridview, need help with this?
here mysql code stored procedure:
SELECT local, SUM(free), SUM(busy), SUM(pause)
FROM (
SELECT local.locations AS local,
CASE car_stat_loc.id_status WHEN 1 THEN 1 ELSE 0 END AS free,
CASE car_stat_loc.id_status WHEN 2 THEN 1 ELSE 0 END AS busy,
CASE car_stat_loc.id_status WHEN 3 THEN 1 ELSE 0 END AS pause
FROM local, car_stat_loc
WHERE local.id_loc = car_stat_loc.id_status
) AS a
GROUP BY local
ORDER BY local
here C# code calling stored procedure:
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
connect.Open();
MySqlCommand camd = connect.CreateCommand();
camd.CommandText = "my_pr2";
camd.CommandType = CommandType.StoredProcedure;
MySqlDataReader rez;
rez = camd.ExecuteReader(CommandBehavior.CloseConnection);
dataGridView3.DataSource = rez;
camd.ExecuteNonQuery();
connect.Close();
}
If I have mistakes, please help to fixed, I am new from this!
first create a static class for my sql helper
using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
namespace MainVoteWeb.Helpers
{
public static class MyHelper
{
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["VoteContext"].ConnectionString;
public static DataTable MyGetData(MySqlCommand command)
{
MySqlConnection connection = new MySqlConnection();
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataTable data = new DataTable();
try
{
connection.ConnectionString = ConnectionString;
command.CommandTimeout = 500;
command.Connection = connection;
adapter.SelectCommand = command;
adapter.Fill(data);
return data;
}
catch (Exception e)
{
return data;
}
finally
{
connection.Close();
}
}
public static int MyExecuteNonQuery(MySqlCommand command)
{
MySqlConnection connection = new MySqlConnection();
int rowsAffected = 0;
try
{
command.CommandTimeout = 500;
connection.ConnectionString = ConnectionString;
connection.Open();
command.Connection = connection;
rowsAffected = command.ExecuteNonQuery();
return rowsAffected.GetString();
}
catch (Exception e)
{
return 0;
}
finally
{
connection.Close();
}
return rowsAffected.ToString();
}
}
}
in the private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["VoteContext"].ConnectionString; change the "VoteContext" into the name of your connection string
i.e
<connectionStrings>
<add name="NewContext" connectionString="Server=127.0.0.1;Database=mysqlvotedb;user id=root; password=" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
should be named as private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["NewContext"].ConnectionString;
then on your button
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
List<local> localList = new List<local>();
MySqlCommand camd = new MySqlCommand();
camd.CommandText = "my_pr2";
camd.CommandType = CommandType.StoredProcedure;
//NOTE: MyExecuteNonQuery is for INSERT UPDATE AND DELETE., MyGetData is for Select/Retrieve
//if the stored procedure has parameter
/*
command.Parameters.AddWithValue("intLocalId", p.localId).Direction = ParameterDirection.Input;
command.Parameters.AddWithValue("strLocalName", p.localName).Direction = ParameterDirection.Input;
*/
try
{
DataTable dt = MyHelper.MyGetData(camd);
foreach (DataRow row in dt.Rows)
{
local item = new local();
item.localId = Convert.ToInt32(row["localId"]);
item.localName = Convert.ToString(row["localName"]);
item.localDetails = Convert.ToString(row["localDetails"]);
localList .Add(item);
}
}
dataGridView3.DataSource = localList ;
dataGridView3.AutogenerateColumns = true;
//no need to open and close the connection. the MyHelper did that already
//camd.ExecuteNonQuery();
//connect.Close();
}
ADVANTAGE: you can use the MyHelper class to any mysql operations, regardless of the class. just provide the name of the stored procedure and execute it
Try this
cmd = new MySqlCommand("ur_sp_name", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Fill(ds);
dg.DataSource = ds;
dg.DataBind();
cn.Close();
I want the DataGridView gets updated when DataTable changes (myAdapter.DeleteCommand = cmd;).
Please help me. Thanks
My code is:
1.
public void DoCommand(String commandText, ActionType actionType, SqlParameter[] sqlParameter)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = getConnection();
cmd.CommandText = commandText;
cmd.Parameters.AddRange(sqlParameter);
if (actionType == ActionType.Insert)
myAdapter.InsertCommand = cmd;
else if (actionType == ActionType.Update)
myAdapter.UpdateCommand = cmd;
else if (actionType == ActionType.Delete)
myAdapter.DeleteCommand = cmd;
cmd.ExecuteNonQuery();
}
}
2.
DataTable dt;
private void frmCustomers_Load(object sender, EventArgs e)
{
dt = obj.SelectCustomer();
dgCustomer.DataSource = localDt;
}
3.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
obj.DoCommand("delete from tbl_customer where customer_id = 1", ActionType.Delete);
}
I want to fill datagridview when rows affected=< 0 but i get error in line 47 gridview (id) = "correctgridview" runat = "server"
the first case work well but the error in the datagridview
mycode
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void insertButton_Click(object sender, EventArgs e)
{
int rowsaffected = 0;
dataset ds = new dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=attend; Integrated Security=true;");
SqlCommand cmd;
cn.Open();
cmd = new SqlCommand("atten", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "#myid";
param.Value = idTextBox.Text;
cmd.Parameters.Add(param);
rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected > 0)
{
resultLabel.Text = "added successful";
}
else
{
resultLabel.Text = "attend error";
SqlCommand command;
command = new SqlCommand("select id, courses.course , course_date , st_lec , location from courses inner join regestration on courses.course = regestration.course where id = 2", cn);
SqlDataAdapter adapte = new SqlDataAdapter(command);
DataTable Dt = new DataTable();
adapte.Fill(Dt);
correctGridView.DataSource = Dt;
correctGridView.DataBind();
}
cn.Close();
}
}