我有两张桌子;
Person
>> Id(PK)(Identity = yes),用户名,.... Barcode
>> Id(FK),条形码,.... 我希望通过会话从表1中获取Id(会话将是用户名)并将该Id插入表2。例如,如果username==session
为真,则插入Id,否则抛出异常。我想将表1的Id插入到table2中,与会话中的相同用户名相关。找到我现在的工作;
public class Service1 : IService1
{
public string InsertUserDetails(UserDetails userInfo)
{
string Message;
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["BCSConnectionString"].ConnectionString;
con.Open();
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select Id from [Person] where username = @session", con))
{
cmd.Parameters.AddWithValue("@session", userInfo.Session);
?????
}
if (exists)
Message = userInfo.Session + "The User Name has not been Registered...!";
else
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Barcode (Id,Barcode,DateTime) values (@Id,@Barcode,@Datetime)", con))
{
cmd.Parameters.AddWithValue("Id", userInfo.Id);
cmd.Parameters.AddWithValue("Barcode", userInfo.Barcode);
cmd.Parameters.AddWithValue("Datetime", userInfo.Datetime);
cmd.Parameters.AddWithValue("Vehicle", userInfo.Vehicle);
cmd.ExecuteNonQuery();
Message = userInfo.Barcode + "All of data Registered ";
}
}
con.Close();
return Message;
}
}
答案 0 :(得分:1)
SqlCommand.ExecuteScalar你需要获得Id。
请记住,您必须将检索到的值转换为所需的数据类型。
int iID = (int)cmd.ExecuteScalar();
我建议进行以下更改:
using
块。SqlCommand
<强>代码强>:
public string InsertUserDetails(UserDetails userInfo)
{
string Message;
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["BCSConnectionString"].ConnectionString;
con.Open();
using (SqlCommand cmd = new SqlCommand("select Id from [Person] where username = @session", con))
{
cmd.Parameters.AddWithValue("@session", userInfo.Session);
int iID = (int)cmd.ExecuteScalar();
if(iID > 0) //check with reference to return ID
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO Barcode (Id,Barcode,DateTime) values (@Id,@Barcode,@Datetime)";
cmd.Parameters.AddWithValue("@Id", iID);
cmd.Parameters.AddWithValue("@Barcode", userInfo.Barcode);
cmd.Parameters.AddWithValue("@Datetime", userInfo.Datetime);
cmd.Parameters.AddWithValue("@Vehicle", userInfo.Vehicle);
cmd.ExecuteNonQuery();
Message = userInfo.Barcode + "All of data Registered ";
}
else
Message = userInfo.Session + "The User Name has not been Registered...!";
}
}
return Message;
}
答案 1 :(得分:1)
我认为您的Id
列是整数,而SELECT
查询返回一个单元格,然后您可以使用ExecuteScalar
方法获取此值。
执行查询,返回第一行的第一列 查询返回的结果集。
int id;
using (SqlCommand cmd = new SqlCommand("select Id from [Person] where username = @session", con))
{
cmd.Parameters.AddWithValue("@session", userInfo.Session);
id = (int)cmd.ExecuteScalar();
}
然后,您可以在id
语句中使用此INSERT
值,就像您在示例中所做的那样;
using (SqlCommand cmd = new SqlCommand("INSERT INTO Barcode (Id,Barcode,DateTime) values (@Id,@Barcode,@Datetime)", con))
{
cmd.Parameters.AddWithValue("@Id", id);
...
cmd.ExecuteNonQuery();
}
另外,我建议您使用using
声明处理您的SqlConnection
。