自学.net(6)DBNULL
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DBNULL { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btn1_Click(object sender, RoutedEventArgs e) { object objName; object objAge; object objHeight; string name=tbName.Text; string age=tbAge.Text; string height=tbHeight.Text; if (name.Length<=0) { objName = DBNull.Value; } else { objName = name; } if (age.Length <= 0) { objAge = DBNull.Value; } else { objAge = name; } if (height.Length <= 0) { objHeight = DBNull.Value; } else { objHeight = height; } SqlHelper.ExecuteNonQuery(@"insert into T_Null(Name,Age,Height) values (@Name,@Age,@Height)", new SqlParameter("@Name", objName), new SqlParameter("@Age", objAge), new SqlParameter("@Height", objHeight)); } private void btn2_Click(object sender, RoutedEventArgs e) { DataTable table= SqlHelper.ExecuteDataTable("select * from T_Null where Id=7"); DataRow row = table.Rows[0]; string name; if (row["Name"]==DBNull.Value) { name = null; } else { name = (string)row["Name"]; } int? age; //int类型不能转换为null值,int?为可空数据类型 if (row["Age"]==DBNull.Value) { age = null; } else { age = (int)row["Age"]; } int? height; if (row["Height"]==DBNull.Value) { height = null; } else { height = (int)row["Height"]; } } } }