如何根据数据库表查询 C# 列表

当我传递列表的字符串版本时,我的代码不会从测试数据库表返回任何行,但如果我直接传递列表成员,它会返回行。


当我使用消息框显示字符串 joinedSerialsList 时,它的格式似乎正确。


// Create comma delimited list of serials:

int currentSerial = beginning;

List<string> serialsList = new List<string>();


for (int i = 0; i < count; i++)

{

     serialsList.Add(currentSerial.ToString());

     currentSerial++;

}


string joinedSerialsList = string.Format("({0})", string.Join(", ", serialsList));


OleDbConnection connection = BadgeDatabaseDB.GetConnection();

string checkStatement

     = "SELECT SerialNumber, OrderNumber "

     + "FROM SerialNumbersMFG "

     + "WHERE SerialNumber IN (@List)";


OleDbCommand command = new OleDbCommand(checkStatement, connection);

command.Parameters.AddWithValue("@List", joinedSerialsList);


string duplicateSerials = "";


try

{

    connection.Open();

    OleDbDataReader dataReader = command.ExecuteReader();


    if (dataReader.Read())

    {

        duplicateSerials += dataReader["OrderNumber"].ToString() + "\n";

    }

}

catch (OleDbException ex)

    {

        throw ex;

    }

finally

    {

        connection.Close();

    }


return duplicateSerials;


蝴蝶刀刀
浏览 126回答 1
1回答

潇潇雨雨

我重写了你的样本,这项工作:&nbsp; &nbsp; private IEnumerable<string> getData()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Create comma delimited list of serials:&nbsp; &nbsp; &nbsp; &nbsp; int currentSerial = 4452; // your constant&nbsp; &nbsp; &nbsp; &nbsp; var serialsList = new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; var count = 100;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < count; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; serialsList.Add(currentSerial++);&nbsp; &nbsp; &nbsp; &nbsp; var connString = getConnectionString();&nbsp; &nbsp; &nbsp; &nbsp; var results = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; string sqlSelect = $"SELECT SerialNumber, OrderNumber FROM SerialNumbersMFG WHERE SerialNumber IN ({string.Join(",", serialsList)})";&nbsp; &nbsp; &nbsp; &nbsp; using (var connection = new SqlConnection(connString)) // BadgeDatabaseDB.GetConnection();&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using (var command = new SqlCommand(sqlSelect, connection))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; connection.Open();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var dataReader = command.ExecuteReader();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (dataReader.Read())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; results.Add(dataReader["OrderNumber"].ToString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return results;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP