Autor Beitrag
Talemantros
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 444
Erhaltene Danke: 2

Win7 Proff 64bit
C# (VS2013)
BeitragVerfasst: Mo 19.01.15 21:46 
Hallo,
ich habe folgende Abfrage gegen eine Datenbank:

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
        /// <summary>
        /// Gibt zurück, ob der Oktabiner zur Zeit mit einer Maschine gekoppelt wird
        /// </summary>
        /// <param name="uebergabe"></param>
        /// <returns></returns>
        public static long GetLongOktabinerIsCombinedWithMachine(string uebergabe)
        {
            long rueckgabe = 0;
            strSQl = "Select maschgrundid from oktabinergrund where oktnummer=?oktnummer";

            using (MySqlConnection conn = new MySqlConnection(connStr))
            {
                using (MySqlCommand cmd = new MySqlCommand(strSQl, conn))
                {
                    conn.Open();

                    cmd.Parameters.AddWithValue("?oktnummer", uebergabe);
                    rueckgabe = Convert.ToInt64(cmd.ExecuteScalar());

                    conn.Close();
                }
            }

            return rueckgabe;
        }


Das Datenbankfeld selber könnte aber null sein.
Nun kommt ein Fehler, dass er DBNull nicht umwandeln kann.

Wie könnte ich damit am besten umgehen?

Danke

Gruß
Daniel
Ralf Jansen
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 4701
Erhaltene Danke: 991


VS2010 Pro, VS2012 Pro, VS2013 Pro, VS2015 Pro, Delphi 7 Pro
BeitragVerfasst: Mo 19.01.15 22:29 
Was soll denn in der Anwendung draus werden? 0, null oder noch was anderes?

Edit: Wen es null oder der typspezifische Default sein soll hilft folgende kleine Methode für die Standardtypen

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
public static T ConvertFromDB<T>(object value)
{
    if ((value == DBNull.Value) || (value == null))
        return default(T);
    else
        return (T)Convert.ChangeType(value, typeof(T));
}

public static long? GetLongOktabinerIsCombinedWithMachine(string uebergabe)
{
   // blah
   return ConvertFromDB<Int64?>(cmd.ExecuteScalar());
}
Talemantros Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 444
Erhaltene Danke: 2

Win7 Proff 64bit
C# (VS2013)
BeitragVerfasst: Di 20.01.15 12:49 
Hey Ralf,
vielen Dank wieder mal für die Hilfe.
Habe den Quelltext nachvollzogen und eingebaut.

Funktioniert einwandfrei.

Gruß
Daniel