1

我有桌子

Resource

ResourceId |  ResourceName |username   | password     
  1        |   raghu       |   aaaa    |  ******
  2        |   anil        |   bbbb    |  ******          

BugHistory

BugHisoryId | FixedByID  | AssignedByID
   1        |    2       |    1
   2        |    1       |    2

谁的登录名同名用户名来获取资源名称。 FixedByIdforeign key(FixedById) reference Resource(ResourceId)

我的控制器代码

public ActionResult BugHistory(BugTracker_DataHelper bugdatahelepr, string loginname, string EmployeName)
{
    Session["UserName"] = "aaaa";
    loginname = Session["UserName"].ToString();
    //bugdatahelepr.Username = loginname.ToString();
    //var username = bugdatahelepr.Username;

    SqlConnection connection = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MvcBugTracker;Data Source=SSDEV6\SQLEXPRESS");
    connection.Open();
    SqlCommand cmd = new SqlCommand("select ResourceName from Resources where UserName =" + loginname, connection);       

    SqlDataReader dr = cmd.ExecuteReader();

    if (dr.Read())
    {
        bugdatahelepr.FixedByID = Convert.ToInt16(dr["ResourceName"]);
        //updatemodel.ProjectId = Convert.ToInt16(dr["ProjectId"]);
    }
    else
    {
        dr.Close();
    }
    dr.Close();
    connection.Close();

    //ViewBag.BugHistoryId = new SelectList(ToStatusDropdown(), "BugHistoryId", "ToStatus");
    //ViewData.AssignedToID=new SelectList()

    return View();
}

我的查看代码

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Gridview_BugTracker.Models.BugTracker_DataHelper>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>BugHistory</title>
</head>
<body>
    <div>

     <%: ViewBag.Title = "BugHistory"%>
     <% using (Html.BeginForm())
     { %>      
      <%:Html.ValidationSummary(true)%>      

        <fieldset>
        <legend>BugHistory</legend>

       <div class="editor-label">
           <%:Html.LabelFor(model => model.FixedByID)%>
        </div>
        <div class="editor-field">
            <%:Html.LabelFor(model => model.FixedByID)%>
            <%:Html.ValidationMessageFor(model => model.FixedByID)%>
        </div>
        <div class="editor-label">
       <%:Html.LabelFor(model => Model.Resolution)%>
     </div>
     <div class="editor-field">
       <%:Html.EditorFor(model => model.Resolution)%>
       <%:Html.ValidationMessageFor(model => model.Resolution)%>
     </div>
       <%: Html.DropDownList("BugHistoryId", (SelectList)ViewBag.BugHistoryId, "--Select Project--")%>
       <%: Html.ValidationMessage("BugHistoryId")%>
       </fieldset> 

       <% }%> 
        <form action="AssignProject.aspx" method="post">  
            <p> <input type="submit" value="insert" /></p> 
             </form>           


    </div>
</body>
</html>

我收到错误

Invalid column name 'aaaa'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'raghu'.

Source Error: 


Line 270:            SqlCommand cmd = new SqlCommand("select ResourceName from Resources where UserName =" + loginname, connection);       
Line 271:          
Line 272:            SqlDataReader dr = cmd.ExecuteReader();
Line 273:            
Line 274:            if (dr.Read())


Source File:     C:\Raghu\Gridview_BugTracker\Gridview_BugTracker\Controllers\ProjectsController.cs    Line: 272 

当我登录页面时,用户名 aaaa 获取资源名称。谁能帮我这样做?

IN veiw page i Diplay like this

FixedBYID -----------raghu <---Lable in disabale

AssignedBY ID-------- anil <----dropdownlist in disable
4

2 回答 2

2

您应该在此代码中改进几件事。首先,总是(我的意思是总是)将连接和数据读取器包装在一个using语句中。

其次,不要连接字符串来构建 SQL 查询。这将使您面临 SQL 插入攻击。相反,您应该使用参数。

现在,对于您看到的错误。您只需将用户名附加到查询中,这将使您的查询如下所示:

select ResourceName from Resources where UserName =aaaa

用户名没有被引用,这意味着数据库服务器将尝试查找名为“aaaa”的列。这正是您看到的错误消息。

您的数据访问代码应如下所示:

using( var connection = new SqlConnection(@".... your connection string here ...") )
{
  connection.Open();

  var cmd = new SqlCommand("select ResourceName from Resources where UserName =@username", connection);       
  cmd.Parameters.Add( name, DbType.String ).Value = loginName;

  using( var reader = cmd.ExecuteReader() )
  {
    if (dr.Read())
    {
        // read your data here
    }
  }
}
于 2012-07-24T07:28:29.003 回答
0

您收到错误是因为:

  • 你没有使用引号 - 在 sql 字符串常量需要包含在 ''
  • 你做错了:你应该使用参数而不是连接字符串
于 2012-07-24T07:31:58.560 回答