cmd.executenonquery显示(不能包含空值)ERROR!
以下是
背后的代码我正在尝试将数据插入到文本框中并发送到数据库中的表,但它一直显示为NULL。
SqlConnection con = new SqlConnection("Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into TableMaleFemale(Name,EiD,Gender) values ('" + NametextBox.Text + "', '" + EiDtextBox.Text + "', '" + GendertextBox.Text + "')", con);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
}
答案 0 :(得分:2)
您应该使用代码更改三件事:
using
语句块很方便如果我进行了这些更改,您的代码就不会更像:
String connectionString = "Data Source=*******;Initial Catalog=MaleFemale;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "insert into TableMaleFemale(Name,EiD,Gender) values (@Name, @EiD, @Gender)"
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@Name").Value = NametextBox.Text == null ? DBNull.Value : NametextBox.Text;
cmd.Parameters.Add("@EiD").Value = EiDtextBox.Text == null ? DBNull.Value : EiDtextBox.Text;
cmd.Parameters.Add("@Gender").Value = GendertextBox.Text == null ? DBNull.Value : GendertextBox.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
这三件事中的任何一件都不能解决您所陈述的问题,但它会解决您尚未拥有的其他问题。