-2

我正在尝试从字符串数组中选择一个随机元素并将其保存在我的数据库中。

OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string Update = string.Format("UPDATE Ships SET InPort=True");
OleDbCommand myCommandUpdt = new OleDbCommand(Update);
myCommandUpdt.Connection = myConnection;
myCommandUpdt.ExecuteNonQuery();
OleDbDataReader drdrShipsRead = myCommandUpdt.ExecuteReader();

string[] Randominporta = { "True", "False", "False" };
// Testlabel.Text = Convert.ToString(Randominport[randomNumber]);

int iNumber = 1;
while (drdrShipsRead.Read())
{
    int randomNumber = random.Next(0, 3);
    string myAddingQuery = string.Format(" UPDATE Ships SET InPort= " + Convert.ToString(Randominport[randomNumber]) + " WHERE ID= " + iNumber + "");
    OleDbCommand myCommand = new OleDbCommand(myAddingQuery);

   string myCommand.Connectionresult = myConnection;
    myCommand.ExecuteNonQuery();
    iNumber++;
}

这没用。

4

3 回答 3

2

简单的方法是:

var a = new List<string> { "True", "False", "False" };

int index = random.Next(strings.Count);
var name = a[index];
a.RemoveAt(index);
return name;
于 2012-10-22T10:50:36.273 回答
1

感谢@CodesInChaos,我认为问题中的代码通常是正确的,但您没有正确声明您的数组,

尝试,

var randomImport = new [] { "True", "False", "False" };

这样做会不那么脆弱

var randomImport = new [] { "True", "False", "False" };
var randomNumber = random.Next(0, randomImport.Length);

或者,

var randomNumber = random.Next(
    randomImport.GetLowerBound(0),
    randomImport.GetUpperBound(0) + 1);
于 2012-10-22T10:21:21.673 回答
0

随着 Jodrell 的回答,您应该修改下面的行以包含 SET InPort 值的引号。

    string myAddingQuery = string.Format(" UPDATE Ships SET InPort= '" + Convert.ToString(Randominport[randomNumber]) + "' WHERE ID= " + iNumber + "");
于 2012-10-22T10:24:54.130 回答