Sql sorgusunun sonucunu DataTable olarak almak için aşağıdaki kodu kullanabiliriz.
public static DataTable GetDateTable(SqlCommand sqlCommand, string TableName, string connectionString)
{
SqlDataAdapter sqlDataAdapter;
DataTable dataTable;
SqlConnection sqlConnection = null;
dataTable = new DataTable(TableName);
try
{
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch
{
throw;
}
finally
{
if ((sqlConnection != null) && (sqlConnection.State == ConnectionState.Open))
sqlConnection.Close();
}
}
Metodu çağıralım :
sqlCommand = new SqlCommand("SELECT CustomerName,CustomerSurname,CustomerAge FROM databaseName.dbo.tableName (NOLOCK) where Tarih='20200528'");
sqlCommand.CommandType = CommandType.Text;
CustomerDataTable = GetDateTable(sqlCommand, "CustomerNameSurname", sqlCnnStr)
#Eğer yalnızca müşteri isimlerini almak istersek
string CustomerName = CustomerDataTable.Rows[0]["CustomerName"].ToString();
# Eğer yalnızca yaşlarını almak istersek
int CustomerAge = Int64.Parse(CustomerDataTable.Rows[0]["CustomerAge"].ToString());