i am trying to retrieve some data from mysql(c#,mono), the problem is that if the returned value is null the program crashes, i know it has to do something with the returned null value, because if i want to retrieve something that is in the database it works,can anyone help me with this?
The code:
MySqlConnection dbcon;
dbcon = new MySqlConnection(conString);
try
{
dbcon.Open();
}
catch (Exception)
{
Console.WriteLine("MySQL Database Connection Problem !!!");
}
//readin开发者_JAVA技巧g data from mysql
MySqlCommand dbcmd = new MySqlCommand(sql, dbcon);
MySqlDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()){
txtFirstname.Text = reader["first_name"].ToString();
txtLastname.Text = reader["last_name"].ToString();
imgUser.File = path+reader["photo"].ToString();
expDate = reader["expiration_datetime"].ToString();
usrName = reader["username"].ToString();
}
dbcon.Close();
You are calling the ToString
method on the objects returned by MySQL.
If MySQL returns null
, you'll call the ToString
method on a null
object, giving a NullReferenceException
.
Assuming that the SQL is actually returning strings (not numbers or dates), you can simply cast to a string, like this: (string)reader["username"]
.
If the SQL is returning non-string datatypes, you can call Convert.ToString(reader["username"])
.
Both of these will result in null
if MySQL returns null
.
If you want MySQL null
s to result in something other than null
, use the null coalescing operator, like this: Convert.ToString(reader["username"]) ?? "It's Null!"
.
For instance, let's imagine your "first_name" is null at database; reader["first_name"]
will return null
and it doesn't have a .ToString()
method, so your code fails.
Below, I changed way you get that files; I try to cast it to string and, if I got a null
value, I use that ??
(null-coalescing operator) to return an empty string.
txtFirstname.Text = reader["first_name" ] as string ?? "";
txtLastname.Text = reader["last_name" ] as string ?? "";
imgUser.File = path + reader["photo"] as string ?? "";
expDate = reader["expiration_datetime"] as string ?? "";
usrName = reader["username"] as string ?? "";
HTH
Based on the exception in your comment, it looks like you have a completely different problem somewhere else.
I would guess that you're reading a .resources
file and generating a filename from the SQL query. If so, null
s might cause you to generate an incorrect filename.
You need to debug your code.
so i guess it will help to post the whole code, here it is. i am just trying to activate an account in ldap, by scanning the barcode which is printed on a card. i also retrieve information about the user of that account, from mysql database.
using System;
using System.Collections;
using Gtk;
using MySql.Data.MySqlClient;
using Novell.Directory.Ldap;
public partial class MainWindow: Gtk.Window
{
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
protected virtual void OnEntry1FocusOutEvent (object o, Gtk.FocusOutEventArgs args)
{
string conString = "server=localhost;database=ldap;User ID=someid;password=somepassword;";
string sql = String.Format("Select * From user where barcode='{0}'",txtBarcode.Text);
string path = "/home/path/to/project/Photo/";
string expDate = "";
string usrName = "";
//creating connection with database
MySqlConnection dbcon;
dbcon = new MySqlConnection(conString);
try
{
dbcon.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
//Console.WriteLine("MySQL Database Connection Problem !!!");
}
//reading data from mysql
MySqlCommand dbcmd = new MySqlCommand(sql, dbcon);
MySqlDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()){
txtFirstname.Text = Convert.ToString(reader["first_name"]);
txtLastname.Text = Convert.ToString(reader["last_name"]);
imgUser.File = path+Convert.ToString(reader["photo"]);
expDate = Convert.ToString(reader["expiration_datetime"]);
usrName = Convert.ToString(reader["username"]);
}
dbcon.Close();
//changeing time from sting to datetime
DateTime dt = Convert.ToDateTime(expDate);
DateTime now = DateTime.Now;
txtStatus.Text = dt.ToString();
//checking if the account has expired
if(dt > now){
//connecting with ldap server
string server = "ip of the server";
string dn = "cn=Manager,dc=itc";
string up = "password";
string dn1 = "uid="+usrName+",ou=people,dc=itc";
// Create a new LdapConnection instance
LdapConnection connl = new LdapConnection();
// Connect to the server
connl.Connect(server, 389);
//Bind
connl.Bind(dn,up);
//Modify user in ldap entry
ArrayList modList = new ArrayList();
LdapAttribute attribute;
//Replace the value of loginshell attribute
attribute = new LdapAttribute( "loginShell", "/bin/sh");
modList.Add( new LdapModification(LdapModification.REPLACE, attribute));
LdapModification[] mods = new LdapModification[modList.Count];
//Type mtype=Type.GetType("Novell.Directory.LdapModification");
mods = (LdapModification[])modList.ToArray(typeof(LdapModification));
//Modify the entry in the directory
connl.Modify ( dn1, mods );
txtStatus.Text="Account Activated!";
// Disconnect from server
connl.Disconnect();
}else{
txtStatus.Text="Account Expired!";
}
}
}
精彩评论