【问题标题】:Search data from two different tables that two tables in different databases从两个不同的表中搜索数据,即不同数据库中的两个表
【发布时间】:2015-12-21 17:30:18
【问题描述】:

我在不同的 SQL Server 数据库中有两个表。

  • Database1 : table1 (custid, productid, customername)
  • Database2table2(产品名称、产品 ID、PICE、制造商)

我想显示特定客户购买的所有产品

我的代码:

using System.Data.SqlClient;

string queryString = "Select custID from Table1 where custId ="+ textbox1.text; 
string TempCustID;

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        if (!reader.IsDBNull(0))
        {
            TempCustID = reader[0].ToString();

            String stringprovider = "@database connection string ";
            Sqlconnection con2 = new sqlconnection(stringprovider);
            Con2.open();
            Cmd2.connection=con2;
            Cmd2.commandType = new commandType.text;
            Cmd2.commandText = "select * from Table2 where Productid = @productid";
            Cmd2.parameters.addwithvalue("@productid",TempCustID);
        }
    }
    reader.Close();

    Dataset Ds = new dataset();
    Oledbdataadaptaer da1 = new oledbdataadapter(cmd2);
    Datatable Table2 = new Data table();
    Da1.fill(table2);
    Datagridview2.source = table2;
}

在此我只获得该客户的第一个产品详细信息,它没有一次显示所有产品。

【问题讨论】:

  • 您也应该为您的读者使用using 声明。你的第二个连接也没有处理。
  • 发布一个 pe 回答的问题只有在问题是通用的并且可能对其他人有用时才有意义
  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入

标签: c# sql


【解决方案1】:

更改您的选择语句。使用INNER JOIN 和它们的productid 连接两个表

SELECT * 
FROM Table2 
INNER JOIN Table1 ON TABLE2.productid = Table1.productid 
WHERE Table2.productid = @productid

这将显示两个表中的所有记录,如果您想选择特定表,只需删除 (*) 并替换为您想要的列名。

SELECT 
    Table1.customername, Table2.productname, Table2.productid, 
    Table2.pice, Table2.mfg 
FROM 
    Table2 
INNER JOIN 
    Table1 ON TABLE2.productid = Table1.productid 
WHERE 
    Table2.productid = @productid

希望我上面的示例代码对您有所帮助。 :)

【讨论】:

    【解决方案2】:

    您正在从 Table1 中选择 custID...而不是根据 customerID 从表 1 中选择 productid

    将您的第一个查询修改为:

    string queryString = "Select productid from Table1 where custId ="+ textbox1.text; 
    

    命令也在循环外执行...

    【讨论】:

      【解决方案3】:

      把它分成两种方法。首先将根据条件从数据库一中获取客户 ID。然后将这些客户 ID 传递给第二种方法并获取产品详细信息。您可以从第一种方法创建客户 ID 列表,并在第二种方法中构建 SQL IN 子句。参考 Building SQL “where in” statement from list of strings in one line?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 2012-12-28
        • 2016-08-15
        相关资源
        最近更新 更多