[英]Returning value from Stored Procedure and using it in C#
我創建了一個函數“ Recover(string UserEmail)”,該函數可以在用戶忘記登錄信息時接收用戶的電子郵件。 此函數運行一個名為“ Recover_PassWord”的存儲過程,我希望它返回用戶名和密碼,以便向用戶發送電子郵件。 我不太熟悉用於創建返回此信息的簡單存儲過程的語法。 我也不太熟悉在C#中存儲返回的值,因此我可以利用它。
恢復密碼:
CREATE DEFINER=`root`@`localhost` PROCEDURE `Recover_Password`(IN Email CHAR(40))
BEGIN
SELECT UserName,PassWord FROM userdata
WHERE Email=ContactEmail;
END
恢復(字符串UserEmail):
public ActionResult Recover(string UserEmail)
{
Login model = new Login();
MySqlConnection connect = DbConnection();
MySqlCommand cmd = new MySqlCommand("Recover_PassWord",connect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Email", UserEmail);
MySqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
if (UserEmail == rd["ContactEmail"].ToString())
{
MailMessage msg = new MailMessage();
msg.To.Add(UserEmail);
msg.Subject = "Recovered Login Information";
msg.Body = "Hello," + Environment.NewLine + "Your Login Information: "; //this is where i want to be able to use the returned value
}
}
return null;
}
任何人都對我如何實現這一目標有任何建議和意見?
您必須使用:像這樣打電話,
MySqlCommand cmd = new MySqlCommand("call Recover_PassWord",connect);
如果使用參數:
create procedure Recover_Password(Email char(40))
BEGIN
SELECT UserName,PassWord FROM userdata
WHERE ContactEmail =Email;
end
使用:
String emailInput = "thisIsMyEmailInput";
MySqlCommand cmd = new MySqlCommand("call Recover_Password('" + emailInput + "')",connect);
嘗試下面的代碼。 如果可行,請將答案標記為肯定。 謝謝!
public ActionResult Recover(string UserEmail)
{
Login model = new Login();
MySqlConnection connect = DbConnection();
MySqlCommand cmd = new MySqlCommand("Recover_PassWord",connect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Email", UserEmail);
MySqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
if (UserEmail == rd["ContactEmail"].ToString())
{
try
{
SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");
// set smtp-client with basicAuthentication
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("username", "password");
mySmtpClient.Credentials = basicAuthenticationInfo;
MailMessage msg = new MailMessage();
msg.To.Add(UserEmail);
msg.Subject = "Recovered Login Information";
msg.Body = "Hello," + Environment.NewLine + "Your Login Information: "; //this is where i want to be able to use the returned value
msg.Body += Environment.NewLine + "username:" + (string)rd["username"];
msg.Body += Environment.NewLine + "password:" + (string)rd["password"];
mySmtpClient.Send(msg);
}
catch (SmtpException ex)
{
throw new ApplicationException
("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
}
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.