4

许多关于 C# 中的 SQL 参数的帖子,但我仍然缺少一些东西。我没有收到错误消息,但没有插入数据。什么不见​​了?我有名为 fname、lname、address、city、state 和 zip 的文本框。

 private void enter_button_Click(object sender, EventArgs e)
 {
    string first, last, addy, city1, stat, zippy;
    first = fname.Text; 
    SqlParameter firstparam;
    firstparam = new SqlParameter();
    firstparam.ParameterName = "@first";
    firstparam.Value = first;
    last = lname.Text;
    SqlParameter lastparam;
    lastparam = new SqlParameter();
    lastparam.ParameterName = "@last";
    lastparam.Value = last;
    addy = address.Text;
    SqlParameter addressparam;
    addressparam = new SqlParameter();
    addressparam.ParameterName = "@addy";
    addressparam.Value = addy;
    city1 = city.Text;
    SqlParameter cityparam;
    cityparam = new SqlParameter();
    cityparam.ParameterName = "@city1";
    cityparam.Value = city1;
    stat = state.Text;
    SqlParameter stateparam;
    stateparam = new SqlParameter();
    stateparam.ParameterName = "@stat";
    stateparam.Value = stat;
    zippy = zip.Text;
    SqlParameter zipparam;
    zipparam = new SqlParameter();
    zipparam.ParameterName = "@zippy";
    zipparam.Value = zippy;

    try
    {
        Validate(fname);
        Validate(lname);
        Validate(city);
        Validate(state);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.ToString(), ex);
    }

    try
    {
        exValidate(address);
    }
    catch (Exception ex1)
    {
        throw new Exception(ex1.ToString(), ex1);
    }

    try
    {
        numValidate(zip);
    }
    catch (Exception ex2)
    {
        throw new Exception(ex2.ToString(), ex2);
    }


    string connection = "Data Source=TX-MANAGER;Initial Catalog=Contacts;Integrated Security=True";
    var sqlstring = string.Format("INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City] ,[State],[ZIP]) VALUES {0}, {1}, {2}, {3}, {4}, {5})", @first, @last, @addy, @city1, @stat, @zippy);
    SqlConnection conn = new SqlConnection(connection);
    SqlCommand comm = new SqlCommand();
    comm.CommandText = sqlstring;
    try
    {
        conn.Open();
        //SqlTransaction trans = conn.BeginTransaction();
        //comm.Transaction = trans;
        comm.Parameters.Add("@first", SqlDbType.Text);
        comm.Parameters.Add("@last", SqlDbType.Text);
        comm.Parameters.Add("@addy", SqlDbType.Text);
        comm.Parameters.Add("@city1", SqlDbType.Text);
        comm.Parameters.Add("@stat", SqlDbType.Text);
        comm.Parameters.Add("@zippy", SqlDbType.SmallInt);
    }
    catch (Exception commex)
    {
        throw new Exception(commex.ToString(), commex);
    }
    conn.Close();
}

所以我改变了这个,仍然没有任何反应。

     string connection = "Data Source=TX-MANAGER;Initial Catalog=Contacts;Integrated Security=True";
        var sqlstring = string.Format("INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City] ,[State],[ZIP]) VALUES {0}, {1}, {2}, {3}, {4}, {5})", @first, @last, @addy, @city1, @stat, @zippy);
        SqlConnection conn = new SqlConnection(connection);
        SqlCommand comm = conn.CreateCommand();
        comm.CommandText = sqlstring;
        try
        {
            conn.Open();
            //SqlTransaction trans = conn.BeginTransaction();
            //comm.Transaction = trans;
            comm.Parameters.AddWithValue("@first", first);
            comm.Parameters.AddWithValue("@last", last);
            comm.Parameters.AddWithValue("@addy", addy);
            comm.Parameters.AddWithValue("@city1", city1);
            comm.Parameters.AddWithValue("@stat", stat);
            comm.Parameters.AddWithValue("@zippy", zippy);
            comm.ExecuteNonQuery();
4

5 回答 5

6

你忘了执行命令;)

编辑:您也没有使用在方法开始时创建的参数。

    ...
    try
    {
        conn.Open();
        //SqlTransaction trans = conn.BeginTransaction();
        //comm.Transaction = trans;
        comm.Parameters.Add(firstparam);
        comm.Parameters.Add(lastparam);
        comm.Parameters.Add(addressparam);
        comm.Parameters.Add(cityparam);
        comm.Parameters.Add(stateparam);
        comm.Parameters.Add(zipparam);

        // This is what you forgot:
        comm.ExecuteNonQuery();
    }
    ...

顺便说一句,不要做这样的事情:

    catch (Exception ex1)
    {
        throw new Exception(ex1.ToString(), ex1);
    }

它没用,它只是增加了一个新级别的异常,而没有添加任何有用的东西。只需让异常在堆栈中冒泡,直到它到达一个实际有用的 catch 块。

于 2012-06-05T14:02:15.953 回答
5

提供的示例中的关键问题是:

  • 的定义sqlstring应该有字符串中的参数定义
  • 通过创建新的错误对象引发错误时正在重置调用堆栈
  • 和对象未正确开始处理(例如,SqlConnection调用不是异常处理程序部分的一部分。SqlCommandconn.Close()Finally
  • ValueSqlParameters设置
  • 对象上的Executexx 方法SqlCommand未开始调用
  • 字符串值存储在一个varchar类型中,而不是Text. Text 是已弃用的用于存储 blob 的 SQL Server 数据类型。

我将重构代码如下:

     private void enter_button_Click(object sender, EventArgs e)
     {
        var first = fname.Text; 
        var last = lname.Text;
        var addy = address.Text;
        var city1 = city.Text;
        var stat = state.Text;
        var zippy = zip.Text;

        Validate(fname);
        Validate(lname);
        Validate(city);
        Validate(state);
        exValidate(address);
        numValidate(zip);

        using (var conn = new SqlConnection("Data Source=TX-MANAGER;Initial Catalog=Contacts;Integrated Security=True"))
        using (var cmd = new SqlCommand(@"INSERT INTO Contacts ([First], [Last], [Address], [City], [State], [ZIP]) VALUES (@first, @last, @addy, @city1, @stat, @zippy)", conn))
        {
            cmd.Parameters.AddRange(
                new[]
                    {
                        new SqlParameter(@"first", SqlDbType.VarChar).Value = first,
                        new SqlParameter(@"last", SqlDbType.VarChar).Value = last,
                        new SqlParameter(@"addy", SqlDbType.VarChar).Value = addy,
                        new SqlParameter(@"city1", SqlDbType.VarChar).Value = city1,
                        new SqlParameter(@"state", SqlDbType.VarChar).Value = stat,
                        new SqlParameter(@"zippy", SqlDbType.SmallInt).Value = zippy
                    });
            conn.Open();
            cmd.ExecuteNonQuery();
        }
    }

注意:我更喜欢提供参数的数据类型,因为当没有提供类型时,SqlCE 并不总是能正常工作。

于 2012-06-05T14:27:24.710 回答
3

这会更短:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO Contacts ([First], [Last], [Address], [City], [State], [ZIP]) VALUES (@first, @last, @address, @city, @state, @zip)";

    command.Parameters.AddWithValue("@first", first);
    // or
    // command.Parameters.Add("@first", SqlDbType.Type).Value = first;
    // ...

    connection.Open();
    command.ExecuteNonQuery();
}

但首先这是你错过的:

comm.Parameters.Add(firstparam);
// instead of
// comm.Parameters.Add("@first", SqlDbType.Text);

command.ExecuteNonQuery();
于 2012-06-05T14:06:21.410 回答
2

首先你没有执行命令,你需要调用comm.ExecuteNonQuery();,其次你的 SQL 字符串是错误的。这一行:

var sqlstring = string.Format("INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City],
[State],[ZIP]) VALUES {0}, {1}, {2}, {3}, {4}, {5})", @first, @last, @addy, @city1, 
@stat, @zippy)

只能是:

var sqlstring = "INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City] ,[State],[ZIP]) 
                 VALUES (@first, @last, @addy, @city1, @stat, @zippy)";

第三,您实际上并没有将参数添加到命令中。您可以像这样创建一个参数:

SqlParameter zipparam;
zipparam = new SqlParameter();
zipparam.ParameterName = "@zippy";
zipparam.Value = zippy;

但是您要添加以下内容:

comm.Parameters.Add("@zippy", SqlDbType.SmallInt);

没有参考zipparam。这意味着该值zippy从未实际添加到命令中。您可以使用以下命令在一行中完成所有操作:

comm.Parameters.Add(new SqlParameter(@Zippy, SqlDbType.SmallInt)).Value = zippy;
于 2012-06-05T14:08:15.020 回答
2

有很多方法可以解决它。其中一种方法是将 try 块中的行替换为:

comm.Parameters.AddWithValue("@first", first);
comm.Parameters.AddWithValue("@last", last);
comm.Parameters.AddWithValue("@addy", addy);
comm.Parameters.AddWithValue("@city1", city1);
comm.Parameters.AddWithValue("@stat", stat);
comm.Parameters.AddWithValue("@zippy", zippy);

如果这样做,则不需要所有SqlParameter初始化

你显然需要执行命令:

comm.ExecuteNonQuery();
于 2012-06-05T14:05:24.250 回答