protected void Button2_Click(object sender, EventArgs e)
    {
        string con = "provider=Microsoft.jet.oledb.4.0;data source="; con += Server.MapPath("Northwind.mdb");
        OleDbConnection mycon = new OleDbConnection(con);
        
        int? a;
        string b = txtid.Text;
        string c = txtclassid.Text;
        string d = txtname.Text;
        mycon.Open();
        if (txtage.Text == "")
        {
           
           a =null;
            OleDbCommand mycmd = new OleDbCommand("   insert into studentname(id,classid,name,age) values ('" + b + "','" + c + "','" + d + "',"+a+")", mycon);
            try
            {
                mycmd.ExecuteNonQuery();
                Response.Write("OK");            }
            catch
            {
                Response.Write("failed");
            }
        }
        else
        { a = int.Parse(txtage.Text);
        
            OleDbCommand mycmd = new OleDbCommand("   insert into studentname(id,classid,name,age) values ('" +b+ "','" +c+ "','" +d+ "'," +a+ ")", mycon);
            try
            {
                mycmd.ExecuteNonQuery();
                Response.Write("OK");            }
            catch
            {
                Response.Write("failed");
            }
这段代码中studentname表中id,classid,name是文本属性,age是数字属性,主属性是id,现在我想不在age中输入内容插入数据库,但是无法实现(估计是int类型问题)。除了把当age不输入时设置为0,还有什么其他方法,能是空属性最好。
希望哥哥姐姐们能教我一下。无法实现的最好也留一下言,让我知道这条路是走不通的。谢谢了

解决方案 »

  1.   

     OleDbCommand mycmd = new OleDbCommand("   insert into studentname(id,classid,name,age) values ('" + b + "','" + c + "','" + d + "',"+(a==null?"null":a.ToString())+")", mycon);前提是你Access里的age列是可空的
      

  2.   

    OleDbCommand mycmd = new OleDbCommand("   insert into studentname(id,classid,name,age) values ('" + b + "','" + c + "','" + d + "',"+(a.HasValue ? a.Value.ToString() : "null")+")", mycon);前提是数据库中该字段允许null,已测试。