C#插入数据到sqlserver数据库

TextBox1 = textBox1.Text.Trim();
TextBox2 = textBox2.Text.Trim();
TextBox3 =textBox3.Text.Substring(0, textBox3.Text.IndexOf(" "));
TextBox4 = textBox3.Text.Substring(textBox3.Text.IndexOf(" "));
con.Open();
string str = @"insert into node_treeview(node_name,ll_addr,mapX,mapY) values (TextBox1,TextBox2,TextBox3,TextBox4)";
SqlCommand command = new SqlCommand(str,con);
command.ExecuteNonQuery();
为何插入不进去,怎么把TextBox1,2,3,4的值赋值给sql语句

你这样连编译都通不过,应该是

TextBox1.Text = textBox1.Text.Trim();
 TextBox2.Text = textBox2.Text.Trim();
 TextBox3.Text =textBox3.Text.Substring(0, textBox3.Text.IndexOf(" "));
 TextBox4.Text = textBox3.Text.Substring(textBox3.Text.IndexOf(" "));
 con.Open();
 string str = string.Format(@"insert into node_treeview(node_name,ll_addr,mapX,mapY) values ('{0}','{1}','{2}','{3}')",TextBox1.Text,TextBox2.Text,TextBox3.Text,TextBox4.Text);
 SqlCommand command = new SqlCommand(str,con);
 command.ExecuteNonQuery();


或者直接就是

con.Open();

 string str = string.Format(@"insert into node_treeview(node_name,ll_addr,mapX,mapY) values ('{0}','{1}','{2}','{3}')",textBox1.Text.Trim(),textBox2.Text.Trim(),textBox3.Text.Substring(0, textBox3.Text.IndexOf(" ")),textBox3.Text.Substring(textBox3.Text.IndexOf(" ")));
 SqlCommand command = new SqlCommand(str,con);
 command.ExecuteNonQuery();

追问

哦,我都不知道为啥这么写哦,好像mysql这样写没问题,sqlserver这么烦啊

追答

你如果是用C#连接的mysql,写法基本一样的,注意我不清楚你的数据库里的字段倒底是什么类型的,如果数字库里字段比如说node_name是数字,那node_name对应的'{0}'的单引号就要去掉,变成{0}

温馨提示:答案为网友推荐,仅供参考
相似回答