想实现gridview展示数据,下面textbox加button增加数据,连接了数据库,在textbox里输入数据后点添加,显示的添加成功但是回去看数据库并没有输入的记录。输入主键相同的会显示错误1,不输入点击会错误2.为什么有messagebox提示了添加信息成功了后台还是没有变化。
public partial class table1 : System.Web.UI.Page
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
protected void Button1_Click(object sender, EventArgs e)
{
string concen = txt1.Text;
string vconcen = txt2.Text;
string tyd = txt2.Text;
string tys = txt2.Text;
string peak = txt2.Text;
string peaks = txt2.Text;
string sqlcmd = "SELECT * FROM table1 WHERE concentration=" + concen+ "";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd,conn);
//cmd.Connection = conn;
//cmd.CommandText = "SELECT * FROM table6.1 WHERE concentration=" + concen + "";
try
{
if (cmd.ExecuteScalar() != null)
{
MessageBox.Show("错误1");
}
else
{
sqlcmd = "INSERT INTO table1 VALUES ('" + concen + "','" + vconcen + "','" + tyd + "' ,'" + tys + "','" + peak + "','" + peaks + "')";
if (cmd.ExecuteNonQuery() != 0)
{
MessageBox.Show("添加信息成功!");
}
else
{
MessageBox.Show("添加信息失败!");
}
}
}
catch (Exception ex)
{
MessageBox.Show("错误2" + ex.ToString());
}
conn.Close();
}
}
}