[英]How to get multiple variable from SQL command in set them to local variable using ExecuteScalar in c#
使用此代碼,我從MS Access 2013數據庫中獲取變量並將其存儲到本地變量中:
public static int UpdateDBtCowsCalculatedVariable()
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Cmd.CommandText = "Select BW from tCows";
Connection.Open();
int BW = (int)Cmd.ExecuteScalar();
Connection.Close();
return BW;
}
但是多個變量呢? 我該怎么辦?
我的意思是這樣的:
public static void UpdateDBtCowsCalculatedVariable()
{
//int BW, DaysInMilk, AnimalType;
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Cmd.CommandText = "Select BW, DaysInMilk, AnimalType from tCows";
Connection.Open();
int BW = (int)Cmd.ExecuteScalar();
// int DaysInMilk = (int)Cmd.ExecuteScalar();
// int AnimalType = (int)Cmd.ExecuteScalar();
Connection.Close();
}
為什么不執行ExecuteReader()
? 即使你在技術上只有一條記錄:
public static void UpdateDBtCowsCalculatedVariable()
{
string StrCon = ...
int BW = -1;
int DaysInMilk = -1;
int AnimalType = -1;
using (OleDbConnection Connection = new OleDbConnection(StrCon))
{
Connection.Open();
using (OleDbCommand Cmd = new OleDbCommand())
{
Cmd.Connection = Connection;
Cmd.CommandText =
@"select BW,
DaysInMilk,
AnimalType
from tCows";
using (var reader = Cmd.ExecuteReader())
{
if (reader.Read())
{
BW = Convert.ToInt32(reader.GetValue(0));
DaysInMilk = Convert.ToInt32(reader.GetValue(1));
AnimalType = Convert.ToInt32(reader.GetValue(2));
}
}
}
}
}
嘗試這個:
public static void UpdateDBtCowsCalculatedVariable() {
//int BW, DaysInMilk, AnimalType;
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Cmd.CommandText = "Select BW, DaysInMilk, AnimalType from tCows";
Connection.Open();
reader = Cmd.ExecuteReader();
while (reader.Read())
{
int BW = reader.GetValue(0);
int DaysInMilk = reader.GetValue(1);
int AnimalType = reader.GetValue(2);
}
reader.Close();
Connection.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.