插入空值.. [英] Inserting null values ..
问题描述
大家好.
请查看我的代码.
dal.cs
public int save(字符串名称,int年龄)
{
con.Close();
con.Open();
cmd = new SqlCommand(插入到Akhil值(""+名称"," + age +)",con);
int temp = cmd.ExecuteNonQuery();
返回温度;
}
aspx.cs
受保护的void Button1_Click(对象发送者,EventArgs e)
{
int = dl.save(TextBox1.Text,Convert.ToInt32(TextBox2.Text));
如果(t> 0)
Response.Write("U do it");
其他
Response.Write("Oops ..!");
}
}
}
现在,当我将文本框留空时,它会以错误的格式将erroe作为输入字符串.
当我填写条目时,它工作得很好.
但是当我将这些文本框保留为null时,应该将null保存到数据库中.
所以请引导我.
紧急.
Thnaks
Hi all.
Plz view my code.
dal.cs
public int save(string name, int age)
{
con.Close();
con.Open();
cmd = new SqlCommand("insert into Akhil values(''"+name"'',"+age+")", con);
int temp = cmd.ExecuteNonQuery();
return temp;
}
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
int t = dl.save(TextBox1.Text, Convert.ToInt32(TextBox2.Text));
if (t >0)
Response.Write("U do it");
else
Response.Write("Oops..!");
}
}
}
Now when i left textboxes empty it gives erroe as input string in incorrect format.
when i filling the entries it is working very fine.
but when i left these textboxes as null it should save null into database.
so plz guide me.
it''s urgent.
Thnaks
推荐答案
这应该有效:
This should work:
cmd = new SqlCommand("insert into Akhil values(" + (name == null ? "NULL" : "'" + name + "'") +
"," + age.ToString() + ")", con);
尽管您实际上应该使用SqlParameter而不是像这样连接字符串;否则,您就容易遭受SQL注入攻击.做一些谷歌搜索,学习如何使用SqlParameter.
Although you should really be using SqlParameter instead of concatenating strings like that; otherwise, you open yourself up to SQL injection attacks. Do some google searches and learn how to use SqlParameter.
这篇关于插入空值..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!