【问题标题】:My SQL statement reads the first row from a database我的 SQL 语句从数据库中读取第一行
【发布时间】:2016-05-02 16:20:20
【问题描述】:

我一直在尝试为我的网站创建一个基本的内部消息传递系统。它会让我在messages表中插入一个新行,但messages中的sellerID(即itemsupdate表中的userID)返回itemsupdate表中第一行的值。

我希望它将 userID 值插入到 SellerID 字段中。

string message = messagebox.Text;
string itemid = Request.QueryString["itemID"];
string finduser = Session["ID"].ToString();

//comunicate to the web server
string connectionString = WebConfigurationManager.ConnectionStrings["itemsconnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);

// myConnection.ConnectionString is now set to connectionString.

myConnection.Open();
string messages = "SELECT userID FROM itemsupdate INNER JOIN users ON itemsupdate.userID = users.ID";
SqlCommand command = new SqlCommand(messages, myConnection);
int sellerid = Convert.ToInt32(command.ExecuteScalar().ToString());

//add the above variables to the table 'comments6'
string query = "INSERT INTO messages(message, buyerID, sellerID, itemID) VALUES(@message, @finduser, @sellerid, @itemid)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
//create a parameterised object
myCommand.Parameters.AddWithValue("@finduser", finduser);
myCommand.Parameters.AddWithValue("@sellerid", sellerid);
myCommand.Parameters.AddWithValue("@itemid", itemid);
myCommand.Parameters.AddWithValue("@message", message);
myCommand.ExecuteNonQuery();
myConnection.Close();

我没有收到任何错误消息。任何帮助将非常感激。我对 SQL 和 StackOverflow 也比较陌生,所以会遇到新手。

【问题讨论】:

  • command.ExecuteScalar() 根据 select 语句返回一个且仅第一行。
  • 好的@t0mm13b,我该如何解决这个问题?
  • 您正在尝试循环遍历itemsupdate 表以获取userID?您的 sql 没有意义,您的问题也不清楚,itemsupdate 表中的一个卖家有多少行。

标签: c# sql asp.net visual-studio


【解决方案1】:

您的问题似乎出在您的第一个查询中:

SELECT userID 
FROM itemsupdate 
INNER JOIN users ON itemsupdate.userID = users.ID

好的@t0mm13b,我该如何解决这个问题?

您无需对 userId 进行过滤,并且由于您正在执行 ExecuteScalar,因此您只获取了返回的第一行。您可能需要添加一个 where 子句,如

where itemId = @itemid // from your queryString param?  

这样想:

itemId    sellerId
1         1
2         1
3         2

如果您要购买第 3 项,并且需要卖家,请获取查询中返回的第一行,例如:

select sellerId
from table

可以返回 1 或 2。您不限于指定的项目。你想要这个:

select sellerId
from table
where itemId = 3

【讨论】:

    【解决方案2】:

    看看你的SELECT statement: SELECT userID FROM itemsupdate INNER JOIN...

    该语句中没有用于选择特定行的 WHERE 子句。因此,无论世界上发生什么其他事情,SELECT 将始终返回连接中的所有行。由于您请求的是 ExecuteScalar,因此您将在出现的第一行的第一列中获取值。

    想想你的逻辑 - 这是一个“错误”(逻辑错误),而不是编码/语法/语言错误。逻辑错误不会引发异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多