Presentation is loading. Please wait.

Presentation is loading. Please wait.

Opret connection til database. Connectionstring setting.

Similar presentations


Presentation on theme: "Opret connection til database. Connectionstring setting."— Presentation transcript:

1 Opret connection til database

2 Connectionstring setting

3 Connectionstring i app.config

4 Reference for at kunne få fat på connection-data i app.config

5 Connection ved brug af factory og connection-data i app.config // Hent provider og connection string fra app.config filen string conectionName = "ForeningsWindowsApplication.ForeningMini.Database"; System.Configuration.ConnectionStringSettingsCollection conStrCollection System.Configuration.ConfigurationManager.ConnectionStrings; System.Configuration.ConnectionStringSettings conStrSettings = conStrCollection[conectionName]; string provider = conStrSettings.ProviderName; string connectionString = conStrSettings.ConnectionString; // opbyg connection objekt med Facrory klassen System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(provider); System.Data.IDbConnection con = factory.CreateConnection(); con.ConnectionString = connectionString;

6 Læsning af tabel med DataReader System.Data.IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT * FROM Forening"; System.Data.IDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { int tmp_id = int.Parse(dataReader["ID"].ToString()); string tmp_navn = dataReader["Navn"].ToString(); ………………………. } dataReader.Close(); /* luk forespørsel*/ con.Close();

7 Opret ny entitet (række) i tabel Datavariable: string navn System.Data.IDbCommand cmd = con.CreateCommand(); int antalIndsat; cmd.CommandText = "INSERT INTO Forening ” + " (navn)”// id ved autonummerering + " VALUES” + " ('"+navn+"')"; antalIndsat = cmd.ExecuteNonQuery(); /* udfør SQL Update/Insert/Delete */ // hent tildelt autonummererede nøgle cmd.CommandText = "select as lastInsertedKey"; int lastInsertedKey = int.Parse(cmd.ExecuteScalar().ToString()); con.Close();

8 Opdater entitet (række) i tabel Datavariable: string navn og int id System.Data.IDbCommand cmd = con.CreateCommand(); int antalRettet; cmd.CommandText = "UPDATE Forening SET” +" Navn='"+navn+"'” +" WHERE ID="+id; antalRettet = cmd.ExecuteNonQuery(); /* udfør SQL Update/Insert/Delete */ con.Close();

9 Slet entitet (række) i tabel Datavariable: int id System.Data.IDbCommand cmd = con.CreateCommand(); int antalSlettede; cmd.CommandText = "DELETE FROM Forening" + " WHERE ID=" + id; antalSlettede = cmd.ExecuteNonQuery(); /* udfør SQL Update/Insert/Delete */ con.Close();


Download ppt "Opret connection til database. Connectionstring setting."

Similar presentations


Ads by Google