Class C# untuk keperluan akses database SQL Server yang meliputi connection, command, dan adapter classes dapat dilihat pada tabel di bawah. Class tersebut didefinisikan pada namespace System.Data.SqlClient
.
Table SQL Server Database Classes
Class | Description | |
SqlConnection | Koneksi fisik ke Database SQL Server | |
SqlDataCommand | Menjalankan perintah / command SQL pada database | |
SqlDataAdapter | Moves data between the DataSet and the physical Database using a connection and a command | |
SqlDataReader | Untuk meng-iterasi hasil yang dikeluarkan oleh suatu command |
Pada SQL Server ketika diinstall terdapat database Northwind Trader. Contoh di bawah ini kita akan menggunakan database tersebut.
Pada contoh ini kita menggunakan command object secara langsung. Program memanggil methodExecuteReader
object SqlCommand
, yang return-nya adalah SqlReader
object. Kemudian kita menggunakan SqlReader
untuk membaca seluruh record yang dihasilkan.
Listing 15.3
// Example15_3.cs
using System;
using System.Data;
using System.Data.SqlClient;
namespace csbook.ch15 {
class Example15_3 {
static void Main(string[] args) {
// create an open the connection
SqlConnection conn =
new SqlConnection("Data Source=DESKTOP;"
+ "Initial Catalog=Northwind;"
+ "Persist Security Info=True;"
+ "User ID=jeff;Password=password");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Customers";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();
// display the results
while (reader.Read()) {
string output = reader["CompanyName"].ToString();
Console.WriteLine(output);
}
// close the connection
reader.Close();
conn.Close();
}
}
}
Akhmad Daniel Sembiring
vITraining.com
Ligarwangi.com - toserba online
Tidak ada komentar:
Posting Komentar