且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过类将数据发送到SQL

更新时间:2021-11-04 06:45:26

构造函数用于构造(因此名称 - 构造函数)。



将插入代码移动到单独的方法中,并在AFTER实例化类时调用。如果您坚持不这样做,请更改构造函数原型以接受必要的参数。



查看代码后,我得说,这是废话。这样做



The constructor is for "constructing" (hence the name - "constructor").

Move your insert code into a separate method and call if AFTER instantiating the class. If you insist on not doing that, change the constructor prototype to accept the necessary parameters.

After looking at your code, I gotta say, it's crap. Do it this way

public static class DateSetter
{
    public static void SetDate(string name, string sex)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException("name");
        }
        if (string.IsNullOrEmpty(sex))
        {
            throw new ArgumentNullException("sex");
        }
        using (SqlConnection conn = new SqlConnection(@"Data Source=~"))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("insert into [databasename].[tbltxt]([name],[SEX])values(@name,@SEX)", conn))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add(new SqlParameter("@name", name));
                cmd.Parameters.Add(new SqlParameter("@SEX", sex));
                cmd.ExecuteNonQuery();
                MessageBox.Show("data has been sent");
            }
        }
    }
}





您不需要房产或类中的变量。



You don't need properties or variables in the class.


你好jame01,



编码一个单独的方法并将你的插入语句代码移动到该方法并调用那个方法。

因为代码在你的构造函数中你不会得到值。所以它抛出错误。



谢谢
hello jame01,

code a separate method and move your insert statment code to that method and call that method.
since that code is in your constructor you will not get values. so it is throwing the error.

Thanks