0

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

环境 :

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

类 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");

请帮忙谢谢...

4

1 回答 1

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 以及表名后面的额外空间):)

于 2013-04-26T06:53:45.540 回答