NobrIntegrált információs rendszer labor br Adatbázisok kliens oldali programozása/nobr

A VIK Wikiből
A lap korábbi változatát látod, amilyen (vitalap) 2012. október 21., 20:33-kor történt szerkesztése után volt. (Új oldal, tartalma: „{{GlobalTemplate|Infoszak|IIRLaborDBClientProg2006}} __TOC__ ==Kapcsolódó tárgyak, tanfolyamok== * [[SzoftverFejlesztesDotNet|Szoftverfejlesztés .NET platformr…”)
(eltér) ← Régebbi változat | Aktuális változat (eltér) | Újabb változat→ (eltér)
Ugrás a navigációhoz Ugrás a kereséshez

Ez az oldal a korábbi SCH wiki-ről lett áthozva. Az eredeti változata itt érhető el.

Ha úgy érzed, hogy bármilyen formázási vagy tartalmi probléma van vele, akkor kérlek javíts rajta egy rövid szerkesztéssel.

Ha nem tudod, hogyan indulj el, olvasd el a migrálási útmutatót



Kapcsolódó tárgyak, tanfolyamok

Adatbázis kapcsolat létrehozása

Ha szükséges, telepítsük a

Ezen a helyen volt linkelve a(z) instnwnd.zip nevű fájl ("Northwind" link szöveggel) a régi wiki http://wiki-old.sch.bme.hu/bin/view/Infoszak/IIRLaborDBClientProg2006 oldaláról. (Ha szükséged lenne a fájlra, akkor a pontos oldalmegnevezéssel együtt küldd el a wiki
Hiba a bélyegkép létrehozásakor: Nem lehet a bélyegképet a célhelyre menteni
@sch.bme.hu címre a kérésedet)
adatbázist.

Visual Studio 2005-ben

  • View / Server Explorer
  • 3. ikon: Connect
  • Choose Data Source: Microsoft SQL Server
  • Server Name: localhost
  • Database name: Northwind

ADO.Net alapvető funkciói

New C# Console Application: dbDemo.
A connection stringet a Server Explorer/Data Connections/Northwind/Properties-ből lehet kimásolni.

static void Main(string[] args) {
	SqlConnection conn = new SqlConnection();
	conn.ConnectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True";

	SqlCommand cmd = new SqlCommand("SELECT * FROM products", conn);
	cmd.CommandType = CommandType.Text;

	conn.Open();
	SqlDataReader rdr = cmd.ExecuteReader();
	while(rdr.Read()) {
		Console.WriteLine(rdr["ProductId"]);
		Console.WriteLine(rdr["ProductName"]);
		Console.WriteLine(rdr["UnitPrice"]);
		Console.WriteLine();
	}
	rdr.Close();
	conn.Close();
}

Ugyanez kicsit rövidebben:

static void Main(string[] args) {
	using(SqlConnection conn = new SqlConnection(
		"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True")) {
		SqlCommand cmd = new SqlCommand("SELECT * FROM products", conn);

		conn.Open();
		using(SqlDataReader rdr = cmd.ExecuteReader())
			while(rdr.Read())
				Console.WriteLine("{0}\n{1}\n{2}",
					rdr["ProductId"], rdr["ProductName"], rdr["UnitPrice"]);
	}
}

Offline adatelérés DataSet és DataTable segítségével

static void Main(string[] args) {
	using(SqlConnection conn = new SqlConnection(
		"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True")) {

		SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM products", conn);
		DataSet ds = new DataSet();
		adapter.Fill(ds, "Products");

		foreach(DataTable table in ds.Tables) {
			Console.WriteLine(table.TableName);
			foreach(DataRow dr in table.Rows)
				Console.WriteLine("{0}, {1}, {2}",
					dr["ProductId"], dr["ProductName"], dr["UnitPrice"]);
		}
	}
}

Típusos DataSet

  • Projekten New / New Item... / Dataset: NorthWind.xsd
  • Húzzuk rá a Northwind adatbázisból a Products táblát.
static void Main(string[] args) {
	ProductsTableAdapter adapter = new ProductsTableAdapter();
	NorthWind.ProductsDataTable table = new NorthWind.ProductsDataTable();
	adapter.Fill(table);

	foreach(NorthWind.ProductsRow row in table.Rows)
		Console.WriteLine("{0}, {1}, {2}",
			row.ProductID, row.ProductName, row.UnitPrice);
}

Megjegyzés: a generált ProductsDataTable kiegészíthető saját metódusokkal. A ProductsTableAdapter-től balra lévő ikonon dupla katt, és készít egy partial class-t.

Ha változtatunk a táblán, az adapter.Update() utasítással lehet szinkronizálni az adatbázissal. Az Update optimistic módon működik, azaz nem használ lockokat, hanem exception-t dob, ha másik felhasználó módosította közben a táblát.

Önálló feladat

  • Németországi Customer-ek listázása DataReader-rel
  • Kiválasztott Customer országának módosítása SqlCommand-dal
  • Vegyünk fel egy új régiót Central néven típusos DataSet-tel

Megoldás

static void Main(string[] args) {
	String connStr = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True";

	// 1. feladat
	using(SqlConnection conn = new SqlConnection(connStr)) {
		SqlCommand cmd = new SqlCommand("SELECT * FROM customers WHERE country='Germany'", conn);

		conn.Open();
		using(SqlDataReader rdr = cmd.ExecuteReader())
			while(rdr.Read())
				Console.WriteLine("{0}, {1}, {2}",
					rdr["CustomerId"], rdr["ContactName"], rdr["Country"]);
	}

	// 2. feladat
	Console.Write("id = "); String id = Console.ReadLine();
	Console.Write("country = "); String country = Console.ReadLine();
	using(SqlConnection conn = new SqlConnection(connStr)) {
		SqlCommand cmd = new SqlCommand("UPDATE customers SET country=@country WHERE customerid=@id", conn);
		cmd.Parameters.AddWithValue("id", id);
		cmd.Parameters.AddWithValue("country", country);
		conn.Open();
		cmd.ExecuteNonQuery();
	}

	// 3. feladat
	RegionTableAdapter adapter = new RegionTableAdapter();
	NorthWind.RegionDataTable table = new NorthWind.RegionDataTable();
	adapter.Fill(table);
	table.Rows.Add(5, "Central");
	adapter.Update(table);
}

-- Peti - 2006.12.01