无法将值NULL插入“EmpId”列

时间:2015-11-09 19:11:59

标签: c# mysql sql-server winforms

我有一个Employee模型/类和一个等效的Employee数据库。当我将新员工插入数据库时​​,没有年龄值,它不起作用。我正在使用windowsform,我已经在我的数据库中定义了age和maritalStatus列,并且c#代码可以为nullable。

  • 当我在表单中填写所有4个文本框值时,它可以正常工作。
  • 当我填写Firstname,Lastname,age&的文本框时离开结婚 文本框在我的表单中为空,它有效(即它创建了一个新的员工和 在数据库中将Married列设置为null)。
  • 当我为Firstname,Lastname,Married和。填充文本框值时 在我的表单中将Age文本框留空,它不起作用。

请帮助,我不知道我做错了什么。

员工人数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NullableTypeDatabase
{
    public class Employee
    {
        int empID;
        string firstName;
        string lastName;
        int? married;
        int? age;


        public int EmpID
        {
            get { return empID; }
            set { empID = value; }
        }


        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }


        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }


        public int? Married
        {
            get { return married; }
            set { married = value; }
        }

        public int? Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

WINFORM CODE:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NullableTypeDatabase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ClickSaveNewUser(object sender, EventArgs e)
        {
            if (ValidateStringInputFields() && ValidateIntInputFields())
            {
                int? convertAge = int.Parse(txtAge.Text);
                if(NullableTypeDB.AddNewEmployee(txtFname.Text, txtLname.Text, comBoxMaritalStatus.SelectedIndex, convertAge) == 1)
                {
                    MessageBox.Show("A New Employee Record has been Successfully Added");
                }
            }


        }

        private bool ValidateStringInputFields()
        {
            var controls = new[] { txtFname, txtLname};

            bool isValid = true;
            foreach (var control in controls.Where(e => String.IsNullOrEmpty(e.Text)))
            {
                errorProviderTxtBoxes.SetError(control, "Please fill the required field");

                isValid = false;
            }

            return isValid;
        }



        private bool ValidateIntInputFields()
        {
            bool isValid = false;
            int resultAge; 
            if(int.TryParse(txtAge.Text, out resultAge))
            {
                isValid = true;
            }

            return isValid;
        }




    }
}

访问数据库的类别:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace NullableTypeDatabase
{
    public class NullableTypeDB
    {
        public static SqlConnection GetConnection()
        {
            string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\Z\documents\visual studio 2013\Projects\NullableTypeDatabase\NullableTypeDatabase\EmployeeInfo.mdf;Integrated Security=True";

            SqlConnection connection = new SqlConnection(connectionString);
            return connection;

        }


        public static int AddNewEmployee(string fname, string lname, int? maritalStat, int? age)
        {

            int returnAffectedRow;

            SqlConnection con = GetConnection();
            string queryStatement = "INSERT INTO Employee(firstname, lastname, married, age) VALUES (@fname, @lname, @maritalStat, @age)";
            SqlCommand sqlCmd = new SqlCommand(queryStatement, con);
            sqlCmd.Parameters.AddWithValue("@fname", fname);
            sqlCmd.Parameters.AddWithValue("@lname", lname);

            if(maritalStat == 0)
            {
                string convertIndex0 = "True";
                sqlCmd.Parameters.AddWithValue("@maritalStat", convertIndex0);
            }

            else if (maritalStat == 1)
            {
                string convertIndex1 = "False";
                sqlCmd.Parameters.AddWithValue("@maritalStat", convertIndex1);
            }

            else
            {
                sqlCmd.Parameters.AddWithValue("@maritalStat", DBNull.Value);
            }



            //if (age.HasValue)
            //{
            //    sqlCmd.Parameters.AddWithValue("@age", age.Value);

            //}
            //else if (age.GetValueOrDefault() == 0)
            //{
            //    sqlCmd.Parameters.AddWithValue("@age", DBNull.Value);

            //}

           // sqlCmd.Parameters.AddWithValue("@age", age == 0? DBNull.Value : (object)age);
            sqlCmd.Parameters.AddWithValue("@age", age.HasValue? age.Value : (object)DBNull.Value);

            try
            {
                con.Open();
               returnAffectedRow = sqlCmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {

                throw ex;
            }
            finally
            {
                con.Close();
            }
            return returnAffectedRow;
        }




    }
}

2 个答案:

答案 0 :(得分:2)

int? convertAge = int.Parse(txtAge.Text);

这一行是你的问题。你正在解析一个空字符串,它只是失败(我假设)。在这里查找int.TryParse()How to parse a string into a nullable int

答案 1 :(得分:1)

你说代码允许它为null,但它实际上不是。在下面的验证方法中,如果未在文本框中输入有效年龄,则此方法将返回false,因此不会执行更新。

    private bool ValidateIntInputFields()
    {
        bool isValid = false;
        int resultAge; 
        if(int.TryParse(txtAge.Text, out resultAge))
        {
            isValid = true;
        }

        return isValid;
    }

此外,您的按钮中的代码代码假定此行始终存在年龄:

 int? convertAge = int.Parse(txtAge.Text);

如果你想让年龄为空,你需要做这样的事情:

    private bool ValidateIntInputFields()
    {
        if(string.IsNullOrEmpty(txtAge.Text))
             return true;

        bool isValid = false;
        int resultAge; 
        if(int.TryParse(txtAge.Text, out resultAge))
        {
            isValid = true;
        }

        return isValid;
    }

    private void ClickSaveNewUser(object sender, EventArgs e)
    {
        if (ValidateStringInputFields() && ValidateIntInputFields())
        {
            int? convertAge = null;

            if( !string.IsNullOrEmpty(txtAge.Text) )
                convertAge = int.Parse(txtAge.Text);

            if(NullableTypeDB.AddNewEmployee(txtFname.Text, txtLname.Text, comBoxMaritalStatus.SelectedIndex, convertAge) == 1)
            {
                MessageBox.Show("A New Employee Record has been Successfully Added");
            }
        }
    }