gpt4 book ai didi

c# - SQL 查询只运行一次

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:25 24 4
gpt4 key购买 nike

我有以下代码:

SqlConnection con = new SqlConnection(@"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
String Query;

for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
MessageBox.Show(" " + this.dataGridView1.Columns.Count);
MessageBox.Show(" " + this.dataGridView1.Columns[i].Name + " ");
MessageBox.Show(" " + this.dataGridView1.SelectedRows[0].Cells[i].Value + " ");

Query = "insert into [" + this.comboBox1.Text + "] ([" + this.dataGridView1.Columns[i].Name + "]) Values ('" + this.dataGridView1.SelectedRows[0].Cells[i].Value + "') ;";

SqlCommand cmd = new SqlCommand(Query, con);

con.Open();

DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(Query, con);

cmd.CommandType = CommandType.Text;
cmd.Connection = con;

sda.SelectCommand = cmd;

sda.Fill(dt);

BindingSource bSource = new BindingSource();
bSource.DataSource = dt;

dataGridView1.DataSource = bSource;
}
con.Close();

它应该将特定值插入表的每一列(显示在 dataGridView 中),但在保存第一个值(我们要插入的行的第一列的值)后,它会刷新表并只有第一个值被插入...我想插入整行

最佳答案

代码按预期正确运行。

这是你的代码:

for each column
build sql string to take first row, current column and insert in db
create sql command using the above sql string
execute the above command
refresh datagrid
next

以上产生了您正在经历的确切行为,这是预期的并且是正确的,因为代码完全按照它被告知的去做。

根据您的描述,您的代码应该是什么:

for each row
build base sql statement
for each column
add current value and field name to the base statement
next
create sql command
fill the command with the statement built in the previous cycle
execute the sql statement
next
refresh datagrid

如果您只需要插入一行,则不需要外部 foreach
在执行字符串连接以构建语句时,请注意输入清理和数据类型。

关于c# - SQL 查询只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31649800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com