本文介绍了关于在数据库中插入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public partial class Home : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=LENOVO-PC\\SQLEXPRESS;Initial Catalog=employee;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e){}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
string s = "insert into employee values('" + TextBox1.Text + "', '" + TextBox2.Text + "', " + " '" + TextBox3.Text + "') ";
SqlCommand comm = new SqlCommand(s, con);
com.ExecuteNonQuery();
con.Close();
推荐答案
com.ExecuteNonQuery() should be comm.ExecuteNonQuery()
另外,我会在你的其他代码所在的范围内声明你的SqlConnection。
Also, I would declare your SqlConnection in the same scope your other code is in.
INSERT INTO EMPLOYEE (col1,col2,col3) Values(val1,val2,val3);
此外,当您将值直接从TextBox放入SQL语句时,您的软件很容易受到SQL注入攻击。最佳做法是使用SQLParameter类将值传递给参数化SQL语句。它也比在SQL语句中嵌入变量值时表现更好。
Also, when you put values directly from a TextBox into a SQL statement, your software is vulnerable to SQL Injection attacks. Best practice is to use SQLParameter Class to pass values to a parameterized SQL statement. It also performs better than when the variable value is embedded within the SQL statement.
INSERT INTO EMPLOYEE (col1,col2,col3) Values(@valName1,@valName2,@valName3);
阅读本文: []
这篇关于关于在数据库中插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!