我试图从mysql(c#,mono)中检索一些数据,问题是如果返回的值为null,程序崩溃,我知道它必须对返回的null值做一些事情,因为如果我想要检索数据库中有效的东西,任何人都可以帮我解决这个问题吗?
代码:
MySqlConnection dbcon;
dbcon = new MySqlConnection(conString);
try
{
dbcon.Open();
}
catch (Exception)
{
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 = 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();
答案 0 :(得分:2)
您正在对MySQL返回的对象调用ToString
方法。
如果MySQL返回null
,您将在ToString
对象上调用null
方法,并提供NullReferenceException
。
假设SQL实际上是返回字符串(而不是数字或日期),您可以简单地转换为字符串,如下所示:(string)reader["username"]
。
如果SQL返回非字符串数据类型,则可以调用Convert.ToString(reader["username"])
。
如果MySQL返回null
,这两个都会导致null
。
如果您希望MySQL null
导致null
以外的其他内容,请使用null合并运算符,如下所示:Convert.ToString(reader["username"]) ?? "It's Null!"
。
答案 1 :(得分:1)
例如,让我们假设您的“first_name”在数据库中为空; reader["first_name"]
将返回null
,但它没有.ToString()
方法,因此您的代码失败。
下面,我改变了你获取文件的方式;我尝试将其强制转换为字符串,如果我得到null
值,则使用??
(null-coalescing运算符)返回空字符串。
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
答案 2 :(得分:0)
根据评论中的例外情况,您似乎在其他地方遇到了完全不同的问题。
我猜您正在读取.resources
文件并从SQL查询生成文件名。如果是这样,null
可能会导致您生成错误的文件名。
您需要调试代码。
答案 3 :(得分:0)
所以我想这将有助于发布整个代码,就在这里。我只是想通过扫描打印在卡片上的条形码来激活ldap中的帐户。我还从mysql数据库中检索有关该帐户用户的信息。
<小时/>
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!";
}
}
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!";
}
}