【问题标题】:C# Insert Advice PleaseC#插入建议请
【发布时间】:2015-12-13 10:12:44
【问题描述】:

您好,我希望获得有关插入选定表的 C# insert 语句的帮助和建议。

到目前为止,我已经为一个表制作了这个插入函数,但希望帮助制作一个将值插入选定表的函数。

编辑:更新的代码,到目前为止我有什么但有问题

       public bool Insert(Dictionary<string, string> values, string tableName)
    {

       SqlDataAdapter adapter;

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {

              string query = "INSERT INTO" tableName "VALUES({string.Join("," values)})";

               using (SqlCommand command = new SqlCommand(query, conn))

               {
                conn.Open();
                adapter = command.ExecuteAdapter();
               }
            }
            return adapter;
   }
 }
}

这是我要创建的新函数,用于将值插入到选定的表中

public bool insert(Dictionary<string, string> values, string tableName)
        {


            SqlDataAdapter adapter; 

 //statment that takes the input which contains vaules, which are           indexed by the colum names
            //as well as a string which represents the table name



            //conenction open

            //exucute


            //return bool status of insert

请提供任何帮助,我并没有真正盯着新语句只看伪代码。

【问题讨论】:

  • 搜索“遍历字典”。和“使用 sqldataadapter 插入”。我知道你可以做到这一点。 ; )
  • 谢谢,我会试一试

标签: c# mysql crud


【解决方案1】:

试试这个:

    public bool Insert(Dictionary<string, string> values, string tableName)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand()
                {
                    Connection = conn,
                    CommandText = $"INSERT INTO {tableName} VALUES({string.Join(", ", values)})"
                };
                cmd.ExecuteNonQuery();
            }
            return true;
        }
        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
            return false;
        }
    }

另外,如果您使用 .NET 进行编程,我建议您稍微了解一下 .NET 编码风格和大小写约定,这将使您将来的生活更轻松。 ;)

【讨论】:

  • 感谢您的帮助,尽管CommandText = $"INSERT INTO ',' {tableName} VALUES({string.Join("," values)})" tableName 是从我的 getAll 语句的下拉列表中选择的一个表出现错误,但一切似乎都很好。错误是缺少我添加的“,”,但随后我得到了无效的成员声明数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多