MySQL Procedure works in php but not in asp.net (C#) - c#

I have built a website with a MySQL back-end with php as the server language, now i shall build the same site in asp.net
The following procedure is define in the MySQL database:
DELIMITER //
CREATE PROCEDURE Login(
IN Username VARCHAR(16),
IN UserPassword VARCHAR(16),
OUT UID int,
OUT SL INT,
OUT SP VARCHAR(8),
OUT MA BOOL) -- missing admin entry
BEGIN
DECLARE adminID INT DEFAULT -1;
DECLARE lastTimeout DATETIME DEFAULT NULL;
SET UID = -1;
SELECT ID, SecurityLevel, LoginTimeout INTO UID, SL, lastTimeout
FROM User
WHERE User.UserName = Username and User.Password = UserPassword;
IF NOW() > lastTimeout OR lastTimeOut IS NULL THEN
IF lastTimeOut IS NOT NULL THEN
INSERT INTO UserLog (UserID, Date, Action) VALUES (UID, NOW(), 'TIMEOUT');
END IF;
SELECT ID, Password INTO SL, SP
FROM SecurityLevels
WHERE ID = SL;
SELECT UserID INTO adminID
FROM Admin
WHERE UserID = UID;
IF adminID = -1 AND SL = 4 THEN SET MA = TRUE;
ELSE SET MA = FALSE;
END IF;
IF UID != -1 THEN
INSERT INTO UserLog (UserID, Date, Action) VALUES (UID, NOW(), 'LOGIN');
UPDATE User SET User.LoginTimeOut = DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE User.ID = UID;
END IF;
ELSE
SET UID = -1;
END IF;
END //
DELIMITER ;
The user I use is:
CREATE USER 'LOGIN'#'%' IDENTIFIED BY '6Jd8kKi0';
GRANT execute ON procedure b09xxxxx.Login TO 'LOGIN'#'%';
Now, in php I do it like this, and it works like a charm:
$pdo = new PDO('mysql:dbname=b09xxxxx;host=wwwlab.xxx.xxx.se', 'LOGIN', '6Jd8kKi0');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$userID = 0;
$securityLevel = 0;
$securityPassword = "";
//$sql = "SELECT UserName, ID, SecurityLevel FROM User WHERE UserName = '" . $_POST['username'] . "' and Password = '" . $_POST['password'] . "';";
$sql = "CALL Login(:USERNAME, :PASSWORD, #UID, #SL, #SP, #MA);";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':USERNAME', $_POST['username']);
$stmt->bindParam(':PASSWORD', $_POST['password']);
$stmt->execute();
//$q = $pdo->query($sql) or die("ERROR:DB");
$sql = "SELECT #UID, #SL, #SP, #MA;";
$q = $pdo->query($sql) or die("ERROR:DB");
$r = $q->fetch(PDO::FETCH_ASSOC);
But this asp.net (C#) version does not work:
string connectionString = "Server=wwwlab.xxx.xxx.se; Database=b09xxxxx; User ID=LOGIN; Password=6Jd8kKi0; Pooling=false;";
MySqlConnection dbcon = new MySqlConnection(connectionString);
dbcon.Open();
//string query = "CALL Login(:USERNAME, :PASSWORD, #UID, #SL, #SP, #MA);";
//Now changed to this thanks to John Woo
string query = "Login";
MySqlCommand sqlCmd = new MySqlCommand(query, dbcon);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue(":USERNAME", loginUsername.Text);
sqlCmd.Parameters[":USERNAME"].Direction = ParameterDirection.Input;
sqlCmd.Parameters.AddWithValue(":PASSWORD", loginPassword.Text);
sqlCmd.Parameters[":PASSWORD"].Direction = ParameterDirection.Input;
sqlCmd.Parameters.Add(new MySqlParameter("#UID", MySqlDbType.Int64));
sqlCmd.Parameters["#UID"].Direction = ParameterDirection.Output;
sqlCmd.Parameters.Add(new MySqlParameter("#SL", MySqlDbType.Int64));
sqlCmd.Parameters["#SL"].Direction = ParameterDirection.Output;
sqlCmd.Parameters.Add(new MySqlParameter("#SP", MySqlDbType.String));
sqlCmd.Parameters["#SP"].Direction = ParameterDirection.Output;
sqlCmd.Parameters.Add(new MySqlParameter("#MA", MySqlDbType.Byte));
sqlCmd.Parameters["#MA"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT #UID, #SL, #SP, #MA;", dbcon);
DataSet ds = new DataSet();
adapter.Fill(ds, "result");
CustomerGrid.DataSource = ds.Tables["result"];
CustomerGrid.DataBind();
dbcon.Close();http://stackoverflow.com/editing-help
I get the following error:
Procedure or function 'CALL Login(:USERNAME, :PASSWORD, #UID, #SL, #SP, #MA)' cannot be found in database 'b09xxxxx'.
Edit: now this is the new problem: SELECT command denied to user 'LOGIN'#'193.11.99.23' for table 'proc'

I reckon that the error is being generated when calling the .Fill method.
Change the below code;
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT #UID, #SL, #SP, #MA;", dbcon);
DataSet ds = new DataSet();
adapter.Fill(ds, "result");
CustomerGrid.DataSource = ds.Tables["result"];
With;
DataTable table = new DataTable();
table.Columns.Add("UID", typeof(int));
table.Columns.Add("SL", typeof(int));
table.Columns.Add("SP", typeof(string));
table.Columns.Add("MA", typeof(boolean));
table.Rows.Add(sqlCmd.Parameters["#UID"].Value, sqlCmd.Parameters["#SL"].Value, sqlCmd.Parameters["#SP"].Value, sqlCmd.Parameters["#MA"].Value);
CustomerGrid.DataSource = table

Related

How to Pass a List from c# to an oracle procedure

I have a code that sends data as a string list from the textbox to oracle procedure.
I get the values in the textbox below.
public List<string> TxtPieceList()
{
List<string> pieces = new List<string>();
for (int i = 0; i < txtListe.Lines.Count(); i++)
{
pieces.Add(txtListe.Lines[i]);
}
return pieces;
}
There are two variables I sent.
p_piece_id is assigned value from textbox.
p_mother_check is assigned value from checkbox.
Then I pass this data into the procedure :
public void gridDoldur()
{
var annesecilimi = cbMother.Checked;
List<string> gridList = TxtPieceList();
using (OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("Z_LABEL_PRINTER_GR.LabelPieceList", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
try
{
OracleParameter p_piece_id = new OracleParameter();
OracleParameter p_mother_check = new OracleParameter();
p_piece_id.OracleDbType = OracleDbType.Varchar2;
p_mother_check.OracleDbType = OracleDbType.Varchar2;
p_piece_id.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
p_mother_check.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
p_piece_id.Value = from emp in gridList select emp;
p_mother_check.Value = annesecilimi;
cmd.Parameters.Add(p_piece_id);
cmd.Parameters.Add(p_mother_check);
cmd.Parameters.Add("p_rc", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
OracleCommandBuilder commandBuilder = new OracleCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.gridPieceList.Visible = true;
gridPieceList.DataSource = dt;
}
But I get an error in the procedure that returns value by oracle.
OracleParameter value is invalid.
CREATE OR REPLACE PACKAGE BODY Z_LABEL_PRINTER_GR
AS
T_STRING_LIST DEFINAION : TYPE "T_STRING_LIST" AS TABLE OF VARCHAR2(2000)
PROCEDURE LabelPieceList(p_piece_id IN T_STRING_LIST,
p_mother_check IN varchar2,
p_rc OUT sys_refcursor)
IS
BEGIN
IF p_mother_check='False' THEN
OPEN p_rc FOR
SELECT PIECE_NUM_ID,PIECE_ID,ACTUAL_WEIGHT,ACTUAL_THICK,ACTUAL_WIDTH
FROM piece WHERE PIECE_ID IN (SELECT COLUMN_VALUE FROM TABLE(p_piece_id))
ELSE
OPEN p_rc FOR
SELECT PIECE_NUM_ID,PIECE_ID,ACTUAL_WEIGHT,ACTUAL_THICK,ACTUAL_WIDTH FROM piece WHERE PIECE_ID IN(
(SELECT COLUMN_VALUE FROM TABLE(p_piece_id)) AND PH.STATUS=2);
END IF ;
END LabelPieceList;
-- Package body
END Z_LABEL_PRINTER_GR;

Web API to call a stored procedure to insert/update DB

I have been working on creating the Web API that accepts the input parameter and calls a Stored Procedure passing the input parameter we received that insert/updates the Account Table in the Database. Now that is perfectly , but my API also need to select the record which was updated/inserted and return them as response
public class ProjectNameCreationController : ApiController
{
[HttpGet]
public HttpResponseMessage Get(string Account)
{
if (string.IsNullOrEmpty(Account))
{
return Request.CreateResponse(new { error = "Input parameters cannot be Empty or NULL" });
}
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
DbConnection.Open();
SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
command.CommandType = CommandType.StoredProcedure;
//create type table
DataTable table = new DataTable();
table.Columns.Add("AccountID", typeof(string));
table.Rows.Add(Account);
SqlParameter parameter = command.Parameters.AddWithValue("#account_TT", table);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "account_TT";
command.ExecuteNonQuery();
Now I am not sure if we will able to select the record that was now insert/updated as part of the Stored Procedure or will I have to create a Query seperately like below
string strQuery = "select AccountID,CounterSeq from Account where AccountID = #accountID ";
var cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#accountID",Account);
Because I will have to Return the response as AccountID-CounterSeq (Eg: IT-1) when the API is called like http://localhost/api/ProjectNameCreation?Account=IT. How can I deal with this. Any help is greatly appreciated
You have to change your procedure as below it will return a record of last inserted or updated.
**--for insert**
IF #StatementType = 'Insert'
BEGIN
insert into Account (first_name,last_name,salary,city) values( #first_name, #last_name, #salary, #city)
--below line to return last inserted record
select * from Account where accountid= SCOPE_IDENTITY()
END
**--for Update**
IF #StatementType = 'Update'
BEGIN
UPDATE Account SET
First_name = #first_name, last_name = #last_name, salary = #salary,
city = #city
WHERE accountid= #accountid
--below line to return last Updated record
select * from account where accountid = #accountid

C# SQL command line monodevelop

I am running monodevelop on arch linux and I tried to insert some values into a local database , but when I run it from a button the application closes.The file is created and it have all fields.
Here is my code:
SqliteConnection m_dbConnection = new SqliteConnection ("Data Source=GOOD_FOOD.sqlite;Version=3;");
m_dbConnection.Open ();
int id;
string get = "SELECT LAST(id_client) FROM Clienti";
SqliteCommand comSelect = new SqliteCommand (get, m_dbConnection);
int? getid = (int?)comSelect.ExecuteScalar();
if (getid.HasValue) {
id = Convert.ToInt32(getid) + 1;
} else
{
id = 1;
}
// create account
string create = "INSERT INTO Clienti (id_client, parola, nume, prenume, adresa, email) VALUES (#id, #parola, #nume, #prenume, #adresa, #email)";
SqliteCommand createcmd = new SqliteCommand (create, m_dbConnection);
createcmd.Parameters.AddWithValue("#id", id);
createcmd.Parameters.AddWithValue ("#parola", password.Text);
createcmd.Parameters.AddWithValue("#nume", name.Text);
createcmd.Parameters.AddWithValue ("#prenume", secondname.Text);
createcmd.Parameters.AddWithValue("#adresa", address.Text);
createcmd.Parameters.AddWithValue ("#email", email.Text);
createcmd.ExecuteNonQuery ();
m_dbConnection.Close ();
The soulution :
Use try{} catch{} and change id = Convert.ToInt32(getid) + 1; to id = getid.Value +1;
Change "SELECT LAST(id_client) FROM Clienti"; to "SELECT id_client FROM Clienti ORDER BY id_client DESC;";

Procedure has no parameters and arguments were supplied

I want to show the stored procedure but i am getting the error of Procedure SPselcocpd has no parameters and arguments were supplied.
cs page
lbllgintype.Text = com;
lblname.Text = com1;
sqlq = "";
sqlq = "select [name] from admin where userid='" + com1 + "'";
SqlDataAdapter da1 = new SqlDataAdapter(sqlq, con);
DataSet ds = new DataSet();
da1.Fill(ds);
name.Text = "";
name.Text = ds.Tables[0].Rows[0][0].ToString();
SqlCommand cmd = new SqlCommand("SPselcocpd");
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#comname", comname.Text);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataSet dt1 = new DataSet();
da2.Fill(dt1);
con.Open();
brand.Items.Add("<--select-->");
for (int i = 0; i < dt1.Tables[0].Rows.Count; i++)
{
brand.Items.Add(dt1.Tables[0].Rows[i][0].ToString());
}
con.Close();`
SQL STORED PROCEDURE
alter procedure SPselbdralt
#comname varchar(100)
as
begin
select brandname from rpmallot where comname=(select id from companydetails where comname=#comname)
end
please solve my problem as soon as possible I am working on a live project
Please make sure, You are using the correct sp
I want to show the stored procedure but i am getting the error of
Procedure SPselcocpd has no parameters and arguments were
supplied.
In code you are calling different SP SPselcocpd
SqlCommand cmd = new SqlCommand("SPselcocpd"); // Here it is SPselcocpd
And SQL SP is
alter procedure SPselbdralt
Confirm that you are calling the correct SP
You are calling wrong stored procedure.
Change
SqlCommand cmd = new SqlCommand("SPselcocpd");
To
SqlCommand cmd = new SqlCommand("SPselbdralt");

Fail to fill datatable using data adapter

i'm try to match the data with the database and using dataadapter to fill my datatable. if matched, fill the datatable with dataadapter. if not match, show msg. but my username and password is matched with database, it still show msg. under debug mode, username and password is all pass through but not fill in the datatable.
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = connStr;
conn.Open();
string sql = #"select user_id, password, status, role_id, email, contact_no,
last_login_date, created_by, last_update_date, last_update_by
from users where user_id = :userID and password = :pwd";
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameters.Add("userID", OracleType.VarChar).Value = userID;
cmd.Parameters.Add("pwd", OracleType.VarChar).Value = pwd;
DataTable dt = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
adapter.Fill(dt);
if (dt.Rows.Count <= 0)
{
msg = "Invalid Login ID or Password";
}
return dt;
}
}
the dt.Rows.Count is 0. but I checked username and password is exactly same with the database.
SQL:
create procedure sp_authenticate
(
#userId varchar(50),
#pass varchar(50)
)
as
begin
select user_id, password, status, role_id, email, contact_no,
last_login_date, created_by, last_update_date, last_update_by
from users where user_id = #userid and password = #pass
end
C# code:
using (OracaleConnection con=new OracaleConnection())
{
conn.ConnectionString = connStr;
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = "sp_authenticate"; //name of your procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userid", OracleType.VarChar,50).value=userID;
cmd.Parameters.Add("#password", OracleType.VarChar,50).value=pwd;
DataTable dt = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
adapter.Fill(dt);
if (dt.Rows.Count <= 0)
{
msg = "Invalid Login ID or Password"; }
}
return dt;
}

Categories

Resources