想在c#中存储sql select语句的返回值

时间:2017-01-09 21:13:52

标签: c# sql asp.net

我想将来自sql查询的UserId的返回值存储到Usersid变量。但是我无法获取值.FYI UserName是文本。

int usersid;
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString()))
using (SqlCommand command = new SqlCommand())
{
    connection.Open();
    command.CommandText = @"Select UserId from  [dbo].[User] where username= @username";

    command.Parameters.Clear();

    command.Parameters.AddWithValue("@username", currentUser.UserName);
    usersid = (int)command.ExecuteScalar();

    command.CommandText = @"INSERT INTO [dbo].[ClientEmailConfirmation] ([JobNumber],[OrderNumber],[UserId]) VALUES 
                                                     (@JobNumber,@OrderNumber,@UserId)";
    command.Parameters.Clear();
    command.Parameters.AddWithValue("@JobNumber", JobNumberTextBox.Text);
    command.Parameters.AddWithValue("@OrderNumber", OrderNumberTextBox.Text);
    command.Parameters.AddWithValue("@UserId", usersid);
    command.ExecuteNonQuery();

}

我非常感谢你的帮助 谢谢, 甲

3 个答案:

答案 0 :(得分:1)

using (SqlCommand command = new SqlCommand()) 
{
  command.Connection = connection;
  ...

答案 1 :(得分:0)

前言:我正在回答结合之前的两个答案,并提供一些最佳实践。

您的原始代码示例缺少与SqlConnectionSqlCommand相关联的片段(双关语)。您需要以下代码段:

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString()))
using (SqlCommand command = new SqlCommand())
{
    connection.Open();
    command.Connection = connection;
    // Rest of code here.
}

我更喜欢在SqlCommand的构造函数中使用空命令文本分配连接。它始终确保将连接分配给SqlCommand。可以找到更多阅读here on MSDN

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString()))
using (SqlCommand command = new SqlCommand("", connection))
{
    // Do note that you still have to open the connection here.
    connection.Open();
    // Rest of code here.
}

假设您的UserId列是整数类型,那么转换结果应该没问题。

usersid = (int)command.ExecuteScalar();

您应该实例化自己的SqlParameter实例,而不是使用AddWithValue()之外的SqlParameterCollection方法。如果您有可能存在冲突的数据类型,AddWithValue可能会推断出错误的类型,从而导致一些难以诊断的问题。如需进一步阅读,请查看此articleMSDN

command.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar) { Value = currentUser.UserName });

答案 2 :(得分:-1)

将标量结果转换为Int:

         int userId = Convert.ToInt32(command.ExecuteScalar()));