【发布时间】:2015-12-21 17:30:18
【问题描述】:
我在不同的 SQL Server 数据库中有两个表。
- Database1 : table1 (custid, productid, customername)
- Database2:table2(产品名称、产品 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 注入