MVC with no Entity Framework - mysql

From the below source tutorials:
https://www.youtube.com/watch?v=Jt9vSY802mM
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
How do I do the above code samples without Entity Framework, by just using SQL queries?
For example in the above source code, instead of
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
I want to do
DELETE FROM Even WHERE EventID = {0}

FirstOrDefault() in LINQ is equivalent to LIMIT 1 in MySQL, hence the LINQ function can be converted to SQL commands using IF or CASE WHEN like this (assumed commands are running inside a stored procedure):
DELIMITER //
-- 'Events' is a DbSet name by common convention,
-- therefore table name should be 'Event'
CREATE PROCEDURE procedure_name (IN eventID INT)
BEGIN
DECLARE v INT;
SET v = SELECT EventID FROM Event WHERE EventID = eventID LIMIT 1;
CASE WHEN v IS NOT NULL
THEN DELETE FROM Event WHERE EventID = v
ELSE -- do something else
END
-- alternative:
-- IF(v IS NOT NULL, DELETE FROM Event WHERE eventID = v, 0)
-- other stuff here
END//
DELIMITER ;
Note: If EventID is a primary key column, you can remove LIMIT 1 because query result only return single value.
Then, use CALL procedure_name(eventID) or include procedure_name in MySqlCommand to execute it.

Couple of ways:
using raw query in Entity Framework:
Open connection string via SqlConnection and execute:
Pseudo code for method 1:
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#id", 1)); delete id = 1
_context.Database.SqlQuery(sqlDeleteStatement, parameterList);
Pseudo code for method 2:
using(SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=[server_name];Database=[database_name];Trusted_Connection=true";
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
SqlCommand command = new SqlCommand(sqlDeleteStatement , conn);
command.Parameters.Add(new SqlParameter("#id", 1)); //delete id = 1
command.ExecuteNonQuery();
}

Related

.NetCore MariaDb Dapper - How to Execute Stored procedure?

I have an issue executing a stored procedure using Dapper with Mysql (MariaDB).
Here is the stored procedure:
CREATE DEFINER = `user` #`%`
PROCEDURE database.`proc_EnterRow`(
IN `_entity_number` INT(11),
IN `_price` DECIMAL(19, 13),
IN `_valuation_date` DATETIME)
LANGUAGE SQL
NOT DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
INSERT INTO tablename (entity_number,
entity_name,
valuation_date,
units,
price,
investor_code,
currency,
provisional,
isin,
type,
batchno,
maturity_date,
fx_rate,
transaction_id,
bond_reserves,
bond_reserves_percentage,
bond_reserves_conv,
sold,
verified)
SELECT entity_number,
entity_name,
_valuation_date,
units,
_price,
investor_code,
currency,
provisional,
isin,
type,
batchno,
maturity_date,
fx_rate,
transaction_id,
bond_reserves,
bond_reserves_percentage,
bond_reserves_conv,
sold,
verified
FROM tablename2 v
WHERE v.entity_number = _entity_number`;
END;
The stored procedure works fine when I execute from an sql editor using
call proc_EnterRow(111,123.5456,'2021-07-09');
But when I call it from my .Net Core with Dapper ORM I keep getting the error message
Incorrect number of arguments for PROCEDURE database.proc_EnterRow; expected 3, got 0
My code .Net code
DynamicParameters_parameters = new DynamicParameters();
_parameters.Add("#_entity_number", 111, DbType.Int32, SetDirection(parameterDirection), 11);
_parameters.Add("#_price", 123.5501, DbType.Decimal, SetDirection(parameterDirection));
_parameters.Add("#_valuation_date", "2021-01-01", DbType.Date, SetDirection(parameterDirection);
_dapper.Execute("dbname.proc_EnterRow", _parameters, commandType: CommandType.StoredProcedure);
Thank you in advance for your help.
var resulst = _dapper.Query<YourEntity>("dbname.proc_EnterRow",
new { _entity_number = 111, _price = 123.5501, _valuation_date = 2021-07-09},
commandType: CommandType.StoredProcedure);
Seems your are trying to execute a stored procedure on your Maria Db from ASP.NET Core.
You are getting the error because the stored procedure parameters haven't been passed exactly.
You could try this way:
string name = "Kiron Test";
int employeeId = 520520;
int totalPrint = 10;
var enterNewRowInDb = new List<PrinterJob>();
enterNewRowInDb = _context.PrinterJobs
.FromSql("proc_EnterRow {0}, {1},{2}",name,employeeId,totalPrint)
.ToList();
Output:
Another way:
using (var connection = new SqlConnection("Server=ServerName;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "proc_EnterRow";
command.Parameters.AddWithValue("#Name", name);
command.Parameters.AddWithValue("#EmployeeId", employeeId);
command.Parameters.AddWithValue("#TotalPrint", totalPrint);
command.ExecuteNonQuery();
connection.Close();
}
Note: it won't return your select query data. To get that you have to execute a data reader operations.
Hope it would help you. Let me know if you any further concern.

Dataset has no values even though procedure is returning proper value

I have a procedure where I am using OPENJSON to display the Json string as key value pairs. When I execute the procedure, it is returning the expected value bu in controller, the dataset is empty. It only shows the table headers - key, value, type. No data at all. When I use a different very similar procedure, it it seems to work fine. Not sure what is happening. Please help!
Thanks in advance!
This is my procedure:
CREATE PROCEDURE [dbo].[PROC_NH_Journal_Tab1Data]
#EnterpriseId nvarchar,
#exactgroup nvarchar
AS
declare #json nvarchar(max)
set #json=(select Tab2Json from tbl_NH_T_JournalDataPost where
EnterpriseId=#EnterpriseId and GroupName = #exactgroup)
SELECT * FROM
OPENJSON ( #json )
Return 0
And here is my action:
public JsonResult GetAnswersFortab1(string exact)
{
string JSONresult = string.Empty;
string EnterpriseId = "User";
try
{
SqlConnection sqlcon = new SqlConnection(con);
SqlCommand cmd = new SqlCommand("[PROC_NH_Journal_Tab1Data]", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EnterpriseId", EnterpriseId);
cmd.Parameters.AddWithValue("#exactgroup", exact);
sqlcon.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet data;
data = new DataSet();
adapter.Fill(data, "Table2");
DataTable dt1 = data.Tables[0];
ViewBag.getJson = dt1;
}
The procedure when executed, gives a table with key, value pairs. But when I debug,in action, the 'data' is an empty table in 'DataSetVisualizer'. Empty table only with headers(key,value,type).No data is present.
Here is my Print #json from the procedure
key value type
emoji2 2 1
check2 on 1
check5 on 1
check7 on 1
hiddentext weds 1

SimpleJDBCCall handle out paramater with resultset

I am using spring jdbc. I want result set with out param. separately i done but together i am not able to do.
CREATE DEFINER=`xxx`#`%` PROCEDURE `client_xxxx`(
IN p_xxxx TINYINT(1) UNSIGNED,
IN p_result SMALLINT(2) UNSIGNED,
OUT p_result BIT ) BEGIN
IF EXISTS(SELECT 1 FROM xxx WHERE xxx = 1 AND xxx = 1) THEN
SELECT ...;
SET p_result = 0;
ELSE
SELECT ...;
SET p_result = 1;
END IF;
END
spring jdbc code
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName(sp);
List<Map<String, Object>> list = (List<Map<String, Object>>) jdbcCall.execute(paramsArray).get("#result-set-1");
list get the result set with result set how can i get p_result with that.
I find it in simple way that i miss.
public Map<String, Object> xxx(String sp, Object... paramsArray) {
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName(sp);
return jdbcCall.execute(paramsArray);
}
execute() gives two parameters default
i.e.
1) #result-set-1
2) #update-count-1
#result-set-1 result set i.e. select record
and #update-count-1 returns update count. If we want to access result with select statement with out parameter. we just have to declare out parameter. execute() gives all the things in Map<String, Object> type.
So from map we can get all the multiple values that stored procedure returns.
For example my SP like
PROCEDURE xxx(
IN xxxxTINYINT(1) UNSIGNED,
IN xxxSMALLINT(2) UNSIGNED,
OUT p_isconfig BIT
)
BEGIN
SELECT....
SET p_isconfig = 1;
END
So in #result-set-1 i get select result.
and p_isconfig gives me result to. If you have any confusion then you can iterate map and identify that how get return parameters.
Iterator i = map.keySet().iterator();
while ( i.hasNext() ) {
String key = (String) i.next();
String value = params.get( key );
System.out.println("key: " + key + " --- value: " + value) ;
}
This way i found solution after reading many things. If any one have other option for this solution then please share with me.
You can try morejdbc (available in maven central) to call your procedure, it's more laconic and it's type safe:
import static org.morejdbc.SqlTypes.BIGINT;
import static org.morejdbc.NamedJdbcCall.call;
import org.morejdbc.*;
...
private JdbcTemplate jdbcTemplate;
...
Out<Integer> out = Out.of(INTEGER);
jdbcTemplate.execute(call("client_xxxx")
.in("p_xxxx", pValue)
.out("p_result", out));
System.out.println("Result is " + out.get());
For ref_cursor out parameter and Oracle database you can use
Out<List<Record>> out = Out.of(OracleSqlTypes.cursor((rs, idx) -> new Record(rs)));
jdbcTemplate.execute(call("client_xxxx")
.in("p_xxxx", pValue)
.out("p_result", out)); // will auto-close ref-cursor
System.out.println("Got result records: " + out.get());

execute stored procedure in classic asp and return values

I need to call from a asp page a stored procedure I have in SQL 2008 and pass to it two values and at the end return the count of two variables.
this is the stored procedure I have:
/****** STUDATATAB******/
CREATE PROCEDURE StdntReconcileDups #NewSTDNT int = NULL, #OldSTDNT int = NULL output
AS
--use ZLDP01RD;
--count = 9 rows
Select count (*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count = 576 rows
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
-- select duplicate keys with new student# count = 3 rows
select a.STDNT,a.crs,a.CRS_VRSN,a.QSTN,a.SCR
from STUDATA.dbo.STUDATATABa, STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR
-- select duplicate keys with new student# count = 3 rows
select count (*)
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR );
-- delete duplicate keys with new student# 3 rows deleted
WITH STUDENT_CTE
AS
(select a.*
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR ))
delete from STUDENT_CTE;
--Convert student #10826 history records to student #123196, should update 579 rows
UPDATE STUDATA.dbo.STUDATATAB
SET STDNT = #NewSTDNT, LSTUPDT_USER_ID_CD = 'DFERN', LSTUPDT_TS = getDate()
where STDNT = #OldSTDNT;
-- count= 582
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count= 0
Select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
go
I want to insert the code in the if argument so it calls StdntReconcileDups and pass to it the values of KeepSTDNT and RemoveSTDNT
Dim DBConn ' Connection object
If Request.Form("Action") = "Go!" then
Endif
If I got your meaning...then do like below:
SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");
con.open();
After creating SqlConnection you will create Storedprocedure like below:
CREATE PROCEDURE RegionUpdate (#RegionID INTEGER,#RegionDescription NCHAR(50)) AS
SET NOCOUNT OFF
UPDATE Region
SET RegionDescription = #RegionDescription
Create a SqlCommand object with the parameters as the name of the stored procedure that is to be executed and the connection object con to which the command is to be sent for execution.
SqlCommand command = new SqlCommand("RegionUpdate",con);
Change the command objects CommandType property to stored procedure.
command.CommandType = CommandType.StoredProcedure;
Add the parameters to the command object using the Parameters collection and the SqlParameter class.
command.Parameters.Add(new SqlParameter("#RegionID",SqlDbType.Int,0,"RegionID"));
command.Parameters.Add(new SqlParameter("#RegionDescription",SqlDbType.NChar,50,"RegionDescription"));
Specify the values of the parameters using the Value property of the parameters
command.Parameters[0].Value=4;
command.Parameters[1].Value="SouthEast";
Excecute the stored procedure using the ExecuteNonQuery method which returns the number of rows effected by the stored procedure.
int i=command.ExecuteNonQuery();
The code above is the right way...You can replace #KeepSTDNT and #RemoveSTDNT exactly instead of #RegionID and #RegionDescription...I have used it myself...if you wanna more help...tell then
the concept is the exeute your request ... you will get back a recordset which you will iterate over until you get to eof... then you will call next recordset to get to the next result.
... are you looking for something like this?
connectstring = "..."
sql = "StdntReconcileDups '" & NewSTDNT & "','" & OldSTDNT & "'"
set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open sql, connectstring, 3

How to add integer value in sql select query?

I'm working on a project where my sql query is
SELECT Name
FROM techer_reg
LIMIT 3
How can I add an integer value instead of 3?
In the sense, this select query should be look like:
SELECT Name
FROM techer_reg
LIMIT (My integer value)
Try using a parameter:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
int myLimit = 4;
using (SqlCommand com = new SqlCommand("SELECT Name FROM techer_reg LIMIT #LM", con))
{
com.Parameters.AddWithValue("#LM", myLimit);
using (SqlDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
int id = (int)reader["iD"];
string desc = (string)reader["description"];
Console.WriteLine("ID: {0}\n {1}", iD, desc);
}
}
}
}
procedure:
DELIMITER $
create PROCEDURE getData(limit INT)
begin
SET #limit= limit;
PREPARE exec_statment FROM "SELECT Name FROM techer_reg LIMIT limit ?;";
EXECUTE exec_statment USING #limit;
DEALLOCATE PREPARE exec_statment;
end$
DELIMITER ;
and call it using
call getData(3)