当Textbox
属性TextMode
使用Multiline
循环时,我希望将foreach
行的每一行插入一行数据库(逐行)?我使用了这段代码,但它将所有行插入到我的“ChTB”表的一行中。这有什么问题?
string ID = null;
DateTime RegDtTime = DateTime.UtcNow;
SqlConnection con1 = new SqlConnection(connectionString);
string sql1 = "SELECT * FROM ChTB";
SqlCommand command1 = new SqlCommand(sql1, con1);
con1.Open();
foreach (object line_loopVariable in this.Textbox1.Text.Split({ Environment.NewLine }, StringSplitOptions.None)) {
line = line_loopVariable;
ID = line;
string commandText = "insert into ChTB(ID,Visible,RegDtTime,LastDateTime) values(@ID,@Visible,@RegDtTime,@LastDateTime)";
SqlCommand cmdObj = new SqlCommand(commandText, con1);
cmdObj.Parameters.AddWithValue("@ID", ID);
cmdObj.Parameters.AddWithValue("@Visible", "NO");
cmdObj.Parameters.AddWithValue("@RegDtTime", RegDtTime);
cmdObj.Parameters.AddWithValue("@LastDateTime", RegDtTime);
cmdObj.ExecuteNonQuery();
}
con1.Close();
答案 0 :(得分:0)
为什么您使用三个不同的变量来获得相同的值?就这样做:
foreach (var line in myTextBox.Lines)
{
// Use line here.
}
对于插入,不要每次都创建一个新的命令对象并添加新参数。创建一个对象,添加参数,然后每次设置Value
属性,例如
var command = new SqlCommand("INSERT INTO MyTable (SomeColumn) VALUES (@SomeColumn)", connection)
var parameter = command.Parameters.Add("@SomeColumn", SqlDbType.VarChar, 50)
foreach (var line in myTextBox.Lines)
{
parameter.Value = line
// Execute command here.
}