[英]How to add array to a SQL row in C#?
I have an array that I made from an StringBuilder:我有一个由 StringBuilder 创建的数组:
string[] input;
input = sb.ToString().Split(',');
Now I want to insert the data from this "input" array to a SQL row?现在我想将这个“输入”数组中的数据插入到 SQL 行中? The first element in the array must be an integer.
数组中的第一个元素必须是整数。 How can I implement this in a fastest way?
我怎样才能以最快的方式实现这一点?
Thanks in advance for any help or example.在此先感谢您的帮助或示例。
I've read from SQL table, edited, and i've got to the sb and I have:我已经从 SQL 表中读取、编辑过,并且我已经找到了 sb,我有:
{50001,Pingu,C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg,A,Skift 2,Requill,sQ,,,,,S5,,,,,,,Motvikt,,Kvalité_nr_2,,,,,,,,,,,,}
col(0) col(1) col(2) col(3) col(4) col(5) col(6) col(7)
50001 Pingu Pathway A Skift 2 Requill SQ ""
Now i want to save back to SQL.现在我想保存回 SQL。 The columns quantity and names in the SQL are changing.
SQL 中的列数量和名称正在发生变化。 That's why I'm using array.
这就是我使用数组的原因。
Vidor维多
I have tried the following (see code) and now I get the error:我已经尝试了以下(见代码),现在我得到了错误:
Must declare the scalar variable "@Param"必须声明标量变量“@Param”
The cbItems array contains the name of columns in the database. cbItems 数组包含数据库中列的名称。
string[] cbItems;
cbItems = sbItems.ToString().Split(',');
string[] input;
input = sb.ToString().Split(',');
DataSet dataSet = new DataSet();
dataTable = dataSet.Tables.Add();
SqlConnection cn = new SqlConnection(connString);
int firstElement;
Int32.TryParse(input[0], out firstElement);
string sql = "INSERT INTO UserData1 (Anställningsnummer) VALUES (@ID)";
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@ID", firstElement);
cmd.ExecuteNonQuery();
int i = 1;
foreach (string r in input)
{
string paramName = cbItems[i].ToString();
string anyElement= input[i].ToString();
SqlCommand myInsertCmd = new SqlCommand("INSERT INTO UserData1(" + paramName + ") VALUES(@Param)", cn);
cmd.Parameters.AddWithValue("@Param", anyElement);
i++;
myInsertCmd.ExecuteNonQuery();
}
cn.Close();
Am I missing something?我错过了什么吗?
Vidor维多
You'll have to parse the first element in the array to an integer.您必须将数组中的第一个元素解析为整数。
int firstElement;
Int32.TryParse(input[0], out firstElement);
You can then use firstElement
and add it as a SQL Parameter
然后您可以使用
firstElement
并将其添加为SQL Parameter
string sql = "INSERT INTO TABLE (ID) VALUES (@ID)";
SqlCommand cmd = new SqlCommand(sql, _connection);
cmd.Parameters.AddWithValue("@ID", firstElement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.