如何在变量c#中分配select语句结果

时间:2014-09-01 09:47:40

标签: c#-3.0

我想从这些select语句中获取值,然后将此值插入另一个表

if (FileUpload1.HasFile)
{
    strsq = "select max(device_id) from device";
    string str = FileUpload1.FileName;
    FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//uploads//" + str);
    string path = "~/device/uploads/" + str.ToString();
    SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["paetdataConnectionString1"].ConnectionString);
    con1.Open();
    string cmdStr1 = "insert into [dev_img] (strsq,image) values (@id,@path)";
    SqlCommand com = new SqlCommand(cmdStr1,con1);
    com.Parameters.AddWithValue("@id", strsq);
    com.Parameters.AddWithValue("@path", path);
    com.ExecuteNonQuery();
    con1.Close();   
}

1 个答案:

答案 0 :(得分:1)

    strsq = "select max(device_id)as DevID from device";
   //To get the Device ID
    int DevID;
    int.TryParse(dSet.Tables[dTableName].Rows[0]["DevID"].ToString(), out DevID);

    //Assign the value
    com.Parameters.Add("@id", SqlDbType.Int);
    com.Parameters["@id"].Value = DevID;

另外,请确保在连接和命令上使用Using子句,以便关闭连接! :)