假如我们如下图所示设计一张T_Students的表:
其中的Hobby,Height和Birthday字段为可空字段。
接着新建一个WPF项目,其界面如下所示:
通过在TextBox控件中输入将输入的内容导入数据库中。
接着我们在“导入数据”按钮添加方法实现:
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.; Initial Catalog=TestDb;User ID=sa;Password=****"))//Password已经隐藏
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//处理Hobby为空
string hobby=tbHobby.Text;//先将控件中的内容存在字符串变量中
object objHobby;
if (hobby.Length <= 0) //防御性编程习惯
{
objHobby = DBNull.Value; //设置为数据库中的NULL
}
else
{
objHobby = hobby;
}
//处理Height为空
string height = tbHeight.Text;
object objHeight;
if (height.Length <= 0)//防御性编程习惯
{
objHeight = DBNull.Value;
}
else
{
objHeight = height;
}
//处理Birthday为空
string datetime = tbBirthday.Text;
object objDateTime;
if (datetime.Length <= 0)//防御性编程习惯
{
objDateTime = DBNull.Value;
}
else
{
objDateTime = datetime;
}
cmd.CommandText =@"Insert into T_Students(Name,Age,Hobby,Height,Birthday) values
(@Name,@Age,@Hobby,@Height,@Birthday) ";
cmd.Parameters.Add(new SqlParameter("@Name", tbName.Text)); //不可空字段,注意此处千万别写成tbName
cmd.Parameters.Add(new SqlParameter("@Age", tbAge.Text)); //不可空字段,注意此处千万别写成tbAge
cmd.Parameters.Add(new SqlParameter("@Hobby", objHobby)); //可空字段
cmd.Parameters.Add(new SqlParameter("@Height", objHeight)); //可空字段
cmd.Parameters.Add(new SqlParameter("@Birthday", objDateTime)); //可空字段
cmd.ExecuteNonQuery();
MessageBox.Show("导入成功");
}
}
}
如果如下面几幅图导入:
则导入数据库中的结果为:
这样,经过以上步骤就可以通过控件的“空白输入”以数据库中的“NULL”内容导入数据库。
接下来,我们对上面数据库中的记录进行查询(指定查询ID=10010的记录)。
代码如下:
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.; Initial Catalog=TestDb;User ID=sa;Password=*****"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Students where ID=10010";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable table = ds.Tables[0];
DataRow row = table.Rows[0];
string name = (string)row["Name"];//非空字段
int age = (int)row["Age"];//非空字段
//可空字段的处理
string hobby;//string类型可以为空,所以不需要也不能写为string?,否则会出错
if (row["Hobby"] == DBNull.Value)
{
hobby = null;
}
else
{
hobby = (string)row["Hobby"];
}
//可空字段的处理
int? height ; //因为可能为空,所以应该写为int?
if (row["Height"] == DBNull.Value)
{
height = null;
}
else
{
height = (int)row["Height"];
}
//可空字段的处理
DateTime? birthday; //因为可能为空,所以应该写为DateTime?
if (row["Birthday"] == DBNull.Value)
{
birthday = null;
}
else
{
birthday = (DateTime)row["Birthday"];
}
Debug.WriteLine(name);
Debug.WriteLine(age);
Debug.WriteLine(hobby);
Debug.WriteLine(height);
Debug.WriteLine(birthday);
}
}
}
通过断点调试可以发现几个变量的值:
完。。。