我使用newxt查询插入到表中,但我不知道语法是什么用于告诉我需要插入的查询,其中training_id =& dateSelected& ,下面的查询通过使用静态值来测试(2)。
请帮忙。
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,training_id, training,trainingDate,trainingHour, trainingSession)SELECT @Val1,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id = 2";
答案 0 :(得分:4)
使用如下参数:
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
using(SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
SqlCommand command= conn.CreateCommand();
command.CommandText= "INSERT INTO personTraining (name,training_id, training,trainingDate,trainingHour, trainingSession)SELECT @Val1,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id = @trainingID";
command.Parameters.AddWithValue("@trainingID",dateSelected);
command.ExecuteNonQuery();
}
但是,您的查询中还有另一个@Val1
参数;我不知道它来自哪里。
答案 1 :(得分:1)
这是一个基本的例子。我不知道您是如何执行string sql
所以我将使用基于SqlCommand
的示例。
SQL:
INSERT INTO personTraining
(name,training_id, training,trainingDate,trainingHour, trainingSession)
SELECT @Val1,training_id,training,trainingDate,trainingHour,trainingSession
FROM tbl_training
WHERE training_id = @training_id;
C#:
SqlCommand cmd = conn.CreateCommand();
cmd.Parameters.AddWithValue("training_id", dateSelected);
答案 2 :(得分:0)
将另一个Parameter对象添加到SqlCommand对象,并将Parameter的值设置为dateSelected。