插入命令不起作用c#

时间:2013-04-26 05:07:23

标签: c# sql-server-2012 sql-insert

有人可以告诉我这是什么问题吗?

设置:

dbConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\data\db.mdf;Initial Catalog=db;Integrated Security=True"

class db.cs:

public SqlConnection conn = new SqlConnection(Properties.Settings.Default.dbConnectionString);

public object insert(String[] inserts, String table)
    {
        string query        = "INSERT INTO "+table+"";
        int dim             = inserts.Length;
        string[] valores    = new String[dim];
        string[] campos     = new String[dim];
        string camposItems  = "(";
        string valoresItems = "(";

        for (int i = 0; i <= dim - 1; i++)
        {
            string[] item = inserts[i].Split('=');
            if (i > 0)
            {
                campos[i]     = item[0];
                valores[i]    = item[1];
                camposItems  += ","+item[0];
                valoresItems += ",@"+item[0];
            }
            else
            {
                campos[i]     = item[0];
                valores[i]    = item[1];
                camposItems  += item[0];
                valoresItems += "@"+item[0];
            }
        }
        camposItems += ")";
        valoresItems += ")";
        query += camposItems+" VALUES "+valoresItems;
        query += "";

        try
        {
            using (this.conn)
            {
                SqlCommand cmdIns = new SqlCommand(query, this.conn);
                int ix = 0;
                string[] vals = new String[valores.Length];
                foreach (string val in valores)
                {
                    vals[ix] = val;
                    SqlParameter parameter = new SqlParameter();
                    parameter.ParameterName = "@" + campos[ix];
                    parameter.SqlDbType = SqlDbType.NVarChar;
                    parameter.Direction = ParameterDirection.Input;
                    parameter.Value = val;
                    cmdIns.Parameters.Add(parameter);
                    ix++;
                }
                cmdIns.Connection.Open();
                //this.conn.Open();
                //object insertID = cmdIns.ExecuteNonQuery();
                object insertID = cmdIns.ExecuteScalar();
                cmdIns.Connection.Close();
                //this.conn.Close();
                if (insertID != null)
                {
                    return insertID;
                }
                else
                {
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
            return ex;
        }
    }

通话功能:

db db = new db();
String[] valores = new String[2]
     {
         "usuario=" + this.textBox1.Text,
         "clave=" + this.maskedTextBox1.Text
      };
 object insert = db.insert(valores, "usuarios_tb");

请帮助谢谢......

1 个答案:

答案 0 :(得分:0)

以下代码可以防止您遇到的一些问题:

  • 使用将被处理的相同连接。
  • 代码的复杂性已经减少(if / while / for的次数减少),这使得调试变得更容易。
  • 使用ExecuteNonQuery而不是ExecuteScalar。
  • 建议:如果不处理,请不要捕捉异常。不要将异常用作返回值。
  • 建议:使用字典。这样您就不必先将值合并,然后再将它们分开。您还可以保留值的类型。

看看这个:

public int insert(IDictionary<string, object> inserts, String table)
{
    string query = "INSERT INTO " + table + " ";
    List<SqlParameter> parameters = new List<SqlParameter>();
    string camposItems = "(";
    string valoresItems = "(";

    foreach(KeyValuePair<string, object> pair in inserts)
    {
        if (!camposItems.EndsWith("("))
        {
            camposItems += ", ";
            valoresItems += ", ";
        }
        camposItems += pair.Key;
        valoresItems += "@" + pair.Key;
        SqlParameter parameter = new SqlParameter("@" + pair.Key, pair.Value);
        parameters.Add(parameter);
    }
    camposItems += ")";
    valoresItems += ")";
    query += camposItems + " VALUES " + valoresItems;

    using(SqlConnection conn = new SqlConnection(Properties.Settings.Default.dbConnectionString))
    using(SqlCommand cmdIns = new SqlCommand(query, conn))
    {
        cmdIns.Parameters.AddRange(parameters.ToArray());
        cmdIns.Connection.Open();
        return cmdIns.ExecuteNonQuery();
    }
}

并称之为:

    db db = new db();
    Dictionary<string, object> valores = new Dictionary<string, object>
    {
        {"usuario", this.textBox1.Text},
        {"clave", this.maskedTextBox1.Text},
    };
    int rowsInserted = db.insert(valores, "usuarios_tb");

我知道,这并没有真正回答你的问题,但它可能会帮助你和其他人找出真正的问题。并且通过消除复杂性,它已经正常工作(因为Connection和ExecuteNonQuery以及tablename之后的额外空间):)