C# 如何获得数据库中指定列的值.

2025-05-10 03:35:36
推荐回答(1个)
回答1:

int maxAttempts = 3;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string commandText = "select TOP 1 ID from A";
int getID= 0;
for (int j = 0; j < maxAttempts; j++)
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.CommandTimeout = 60;

getID= Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
break;
}
catch (SqlException ex)
{
Console.WriteLine(commandText);
Console.WriteLine(ex.Message + " Retrying...");
getID= -1;
}
}
conn.Close();

LINQ:
var getIDs = from a in myDBContext.A
select a.ID;
int getID = getIDs.MAX(); //FirstOrDefault()