【问题标题】:Getting a success message only if and only data is inserted into Microsoft SQL server database仅当且仅将数据插入 Microsoft SQL Server 数据库时才获得成功消息
【发布时间】:2019-01-05 15:25:21
【问题描述】:

这是我的挑战。我已经成功创建了一个表单,当用户填写并提交时,他/她会在他们的电子邮件收件箱中收到一条成功消息。但现在我的挑战是每当触发提交按钮时,即使数据没有插入数据库,他们仍然会收到成功消息。我不知道我的编码有什么问题。请帮忙。这是我的 C# 代码:

public bool InsertRegistration()
    {
        // Determine the currently logged on user's UserId

        MembershipUser currentUser = Membership.GetUser();
        Guid currentUserId = (Guid)currentUser.ProviderUserKey;

        //Start of Upload 1
        FileUpload img = (FileUpload)AdmissionUpload;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File1 = AdmissionUpload.PostedFile;

            //Create byte Array with file len
            imgByte = new Byte[File1.ContentLength];

            //Get content type
            string contenttype = File1.ContentType;

            //Get file name
            string filename = Path.GetFileName(File1.FileName);

            //force the control to load data in array
            File1.InputStream.Read(imgByte, 0, File1.ContentLength);
        }

        FileUpload img1 = (FileUpload)StudentIDUpload;
        Byte[] imgByte1 = null;
        if (img1.HasFile && img1.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File2 = StudentIDUpload.PostedFile;

            //Create byte Array with file len
            imgByte1 = new Byte[File2.ContentLength];

            //Get content type
            string contenttype1 = File2.ContentType;

            //Get file name
            string filename1 = Path.GetFileName(File2.FileName);

            //force the control to load data in array
            File2.InputStream.Read(imgByte1, 0, File2.ContentLength);
        }

        FileUpload img2 = (FileUpload)TranscriptUpload;
        Byte[] imgByte2 = null;
        if (img2.HasFile && img2.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File3 = TranscriptUpload.PostedFile;

            //Create byte Array with file len
            imgByte2 = new Byte[File3.ContentLength];

            //Get content type
            string contenttype2 = File3.ContentType;

            //Get file name
            string filename2 = Path.GetFileName(File3.FileName);

            //force the control to load data in array
            File3.InputStream.Read(imgByte2, 0, File3.ContentLength);
        }

        FileUpload img3 = (FileUpload)PassportUpload;
        Byte[] imgByte3 = null;
        if (img3.HasFile && img3.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File4 = TranscriptUpload.PostedFile;

            //Create byte Array with file len
            imgByte3 = new Byte[File4.ContentLength];

            //Get content type
            string contenttype3 = File4.ContentType;

            //Get file name
            string filename3 = Path.GetFileName(File4.FileName);


            //force the control to load data in array
            File4.InputStream.Read(imgByte3, 0, File4.ContentLength);
        }


        //SqlDateTime sqldatenull;

        using (var con = new SqlConnection(conStr))
        {
            using (var com = new SqlCommand("INSERT INTO Candidates(FirstName, MiddleName, Surname, DateOfBirth, Phone, Email, DateApplied, CurrentLevel, MatricNo, JAMBNo, UTMEScore, YearOfAdmission, ExpectedYearOfGraduation, NIN, StudyMode, EntryMode, NextOfKin, NextOfKinEmail, NextOfKinPhone, RelationToNextOfKin, AcademicReferee,  AcademicRefereeMobile, RelationWithAcademicReferee,  DirectEntryRegNo, DirectEntryGrade, CurrentGPA, Courseid, Institution, HeadOfDept, HODPhone, HODEmail, RelatedToGovtOfficial, GovtOfficialName, PositionOfGovtOfficial, OnScholarship, ScholarshipName, YearOfScholarship, StateID, LGID, Community, AccountNo, SortCode, UType, AdmissionLetter, AdmissionLetterFileName, AdmissionImageType, StudentID, StudentIDFileName, StudentImageType, Transcript, TranscriptFileName, TranscriptImageType, Passport,  PassportFileName, PassportImageType, Maths, Eng, Subject3, Subject4, Subject5, Subject6, Subject7, Address, FacultyID, GradeSubject3, GradeSubject4, GradeSubject5, GradeSubject6, GradeSubject7, Location, UserId, StateOfResidence, Gender, Bank) VALUES (@FirstName, @MiddleName, @Surname, @DateOfBirth, @Phone, @Email, @DateApplied, @CurrentLevel, @MatricNo, @JAMBNo, @UTMEScore, @YearOfAdmission, @ExpectedYearOfGraduation, @NIN, @StudyMode, @EntryMode, @NextOfKin, @NextOfKinEmail, @NextOfKinPhone, @RelationToNextOfKin, @AcademicReferee,  @AcademicRefereeMobile, @RelationWithAcademicReferee,  @DirectEntryRegNo, @DirectEntryGrade, @CurrentGPA, @Courseid, @Institution, @HeadOfDept, @HODPhone, @HODEmail, @RelatedToGovtOfficial, @GovtOfficialName, @PositionOfGovtOfficial, @OnScholarship, @ScholarshipName, @YearOfScholarship, @StateID, @LGID, @Community, @AccountNo, @SortCode, @UType, @AdmissionLetter, @AdmissionLetterFileName, @AdmissionImageType, @StudentID, @StudentIDFileName, @StudentImageType,  @Transcript, @TranscriptFileName, @TranscriptImageType, @Passport,  @PassportFileName, @PassportImageType, @Maths, @Eng, @Subject3, @Subject4, @Subject5, @Subject6, @Subject7, @Address, @FacultyID, @GradeSubject3, @GradeSubject4, @GradeSubject5, @GradeSubject6, @GradeSubject7, @Location, @UserId, @StateOfResidence, @Gender, @Bank"))
            {
                com.Connection = con;

                com.Parameters.AddWithValue("@FirstName", txtFN.Text);
                com.Parameters.AddWithValue("@MiddleName", txtMN.Text);
                com.Parameters.AddWithValue("@Surname", txtLN.Text);

【问题讨论】:

    标签: c# asp.net sql-server file-upload system.net.mail


    【解决方案1】:

    您在InsertRegistration(); 之前调用smtpClient.Send(msg);,因此您正在发送电子邮件;然后尝试将数据插入数据库中。

    您可能还想按照@Rahul 上面的建议从InsertRegistration(); 返回bool

    虽然你关闭了连接,但不确定你在哪里打开它;因此,如果您在方法中打开它但将其包装在 using 中,您可以跳过 Close 方法(因为使用将关闭它)所以:

    public bool InsertRegistration()
    {
        // ...
        using (var conn = new SqlConnection(...))
        {
            using (var com = new SqlCommand("INSERT INTO Candidates..."))
            {
                com.Parameters.AddWithValue("@FirstName", txtFN.Text);
                // ... etc
    
                con.Open(); // open connection here, just before executing
                // return the true/false for whether a row was inserted
                return com.ExecuteNonQuery() >= 1;
            }
        }
    }
    
    protected void btnsendmail_Click(object sender, EventArgs e)
    {
        using (StreamReader reader = new StreamReader(Server.MapPath("~/Account/RegMessage.html")))
        {
            // ...
    
            if (InsertRegistration())
            {
                // Only run if inserted correclty
                smtpClient.Send(msg);
                lblMessage.Text = "Application submitted successfully! ...";
                lblMessage.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblMessage.Text = "Error submitting application";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            lblMessage.Visible = true;
        }
    }
    

    【讨论】:

    • 感谢本·亚当斯。我已格式化我的代码以适应您的所有建议,但在尝试运行页面时出现错误消息:编译错误描述:在编译服务此请求所需的资源期间发生错误。请查看以下特定错误详细信息并适当修改您的源代码。编译器错误消息:CS0161:“ORMApp_Scholarship_application.InsertRegistration()”:并非所有代码路径都返回值
    • 啊,您正在对每个文件进行插入...您想以 bool inserted = false; 开始该方法,然后将 return com.ExecuteNonQuery() >= 1; 更改为 inserted &= (com.ExecuteNonQuery() >= 1); 并在所有括号外的方法末尾;除了最后一个return inserted;
    • 编译器不知道是否有任何循环会运行
    • 现在只清除我收到错误:ConnectionString 尚未初始化,我已编辑我的代码
    • 您尚未将SqlConnection 添加到SqlCommand。将其作为第二个参数添加到构造函数var com = new SqlCommand("INSERT INTO Candidates...", con) 或在com.Connection = con; 之后设置
    【解决方案2】:

    ExecuteNonQuery 返回受影响的行数,因此您可以更改方法签名以返回相同的类似

    public int InsertRegistration() {
    // all code 
    int rows = com.ExecuteNonQuery();
    return rows;
    }
    

    所以在你的事件处理程序中检查,然后显示类似的消息

        int rows = InsertRegistration(); 
        if(rows > 0) {
        lblMessage.Visible = true;
        lblMessage.Text = "Application submitted successfully! C...";
        }
    

    【讨论】:

    • 谢谢拉胡尔。但这是我的问题,我希望用户只有在将数据插入数据库时​​才能收到成功的电子邮件。在点击提交按钮时,即使数据没有插入数据库,他们仍然会收到一封成功的电子邮件,
    【解决方案3】:

    首先,我建议使用模式 Async Task 来避免在您的应用程序中以某种方式解除锁定。 (见下例)

    其次,正如 Ben 所说,使用 Raul 在他的答案中的逻辑将您的方法返回为布尔值:

    所以请试试这个:

    public async Task<bool> InsertRegistration() 
    {
        // all code
    
        int rows = await com.ExecuteNonQueryAsync();
    
        if(rows>0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
         protected void btnsendmail_Click(object sender, EventArgs e)
        {
            using (StreamReader reader = new 
         StreamReader(Server.MapPath("~/Account/RegMessage.html")))
         {
            // ...
    
            if (InsertRegistration())
            {
                // Only run if inserted correclty
                smtpClient.Send(msg);
                lblMessage.Text = "Application submitted successfully! ...";
                lblMessage.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblMessage.Text = "Error submitting application";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            lblMessage.Visible = true;
        }
        }
    

    【讨论】:

    • 感谢 BerBar。我仍然在 InsertRegistration() 下看到一条红色下划线,表示并非所有代码路径都可以返回值。我该如何解决这个问题。我已经尝试重新编码,但仍然显示
    • @Paschal,抱歉耽搁了。可以向我展示我演示的上述部分,我的意思是 //allcode ?
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2014-10-15
    • 2017-04-21
    • 2022-06-10
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多