DBNull.Value,null,String.Empty之间的区别和联系

本文详细阐述了C#中null、String.Empty和DBNull.Value的概念及区别,包括它们的用途、性能考虑以及在数据库操作中的应用。通过对比分析,帮助开发者理解如何在不同场景下正确使用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,“null”是C#中(VB.NET为Nothing),表示某个引用对象变量“未引用”任何实体时候的状况(典型症状是如果调用这个变量的某个方法,会抛出NullException之类的异常)。

String.Empty是一个静态的公共变量,表示某String变量不包含任何字符(等同于"")。不过从性能上说,用String.Empty比声明用一个""好一些——显然地,前者是String类的静态变量,无论如何使用只产生一个实例,后者用几次恐怕要产生几次了。

至于DBNull.Value,也是一个静态属性。它唯独用于数据库(例如使用DataReader读取数据的时候,又或者是DataTable中某行某列数据的比较时候)的“空数值”比较。因为在SQL中某个字段为Null只是说明该字段“没有任何值”,并不是C#中“不存在引用”。因此注意这些问题:

1)如果用DataReader执行ExecuteScalar,如果你不确定是否会获取数据,必须采用null进行判断(因为空引用);如果你确信读取至少一条数据,但是不确定是否数据为空,可以使用DBNull.Value进行数值判断。

2)承接1,如果某条字段确信没有任何数据,等同于没有任何字符,等同于String.Empty和"",因此完全可以用String.Empty或者""进行判断(重要结论:DbNull.Value=String.Empty="")。

3)另外,如果对string类型的DataColumn进行赋值(譬如赋值为null),既便如此,实际上在DataTable中不可能存一个null(为了和SQL实际数值对应),会转化成String.Empty或者是""。判断方法同“重要结论”。

转载于:https://www.cnblogs.com/ServiceboyNew/archive/2013/06/09/3128067.html

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Configuration; namespace DBUtility { public class DbHelperSQL { // Fields public static string connectionString; // Methods static DbHelperSQL() { connectionString = ConfigurationManager.AppSettings["ConnectionString"]; } public DbHelperSQL() { } private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } public static SqlDataReader ExecuteReader(string strSQL) { SqlDataReader dr; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); dr= cmd.ExecuteReader(); } catch (SqlException e) { throw new Exception(e.Message); } return dr; } public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) { SqlDataReader dr; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(); cmd.Parameters.Clear(); dr = myReader; } catch (SqlException e) { throw new Exception(e.Message); } return dr; } public static int ExecuteSql(string SQLString) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); return cmd.ExecuteNonQuery(); } catch (SqlException E) { connection.Close(); throw new Exception(E.Message); } } } return count; } public static int ExecuteSql(string SQLString, string content) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); count = cmd.ExecuteNonQuery(); } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return count; } public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (SqlException E) { throw new Exception(E.Message); } } } return count; } public static int ExecuteSqlByTime(string SQLString, int Times) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; return cmd.ExecuteNonQuery(); } catch (SqlException E) { connection.Close(); throw new Exception(E.Message); } } } return count; } public static object ExecuteSqlGet(string SQLString, string content) { object esg; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } esg = obj; } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return esg; } public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); SqlParameter myParameter = new SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); count = cmd.ExecuteNonQuery(); } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return count; } public static void ExecuteSqlTran(ArrayList SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (SqlException E) { tx.Rollback(); throw new Exception(E.Message); } } } public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } public static bool Exists(string strSql) { int cmdresult; object obj = GetSingle(strSql); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } return true; } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { int cmdresult; object obj = GetSingle(strSql, cmdParms); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } return true; } public static int GetMaxID(string FieldName, string TableName) { object obj = GetSingle("select max(" + FieldName + ")+1 from " + TableName); if (obj == null) { return 1; } return int.Parse(obj.ToString()); } public static object GetSingle(string SQLString) { object gs; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } return obj; } catch (SqlException e) { connection.Close(); throw new Exception(e.Message); } } } return gs; } public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) { object gs; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } return obj; } catch (SqlException e) { throw new Exception(e.Message); } } } return gs; } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds, "ds"); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString,int pageindx,int pagesize,string tablename) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds,pageindx,pagesize,tablename); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) { DataSet dsq; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (SqlException ex) { throw new Exception(ex.Message); } dsq = ds; } } return dsq; } public static DataSet Query(string SQLString,string tablename) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds, tablename); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; return command.ExecuteReader(); } public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); int result = (int)command.Parameters["ReturnValue"].Value; connection.Close(); return result; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static void RunStatProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); connection.Close(); } } } }
最新发布
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值