关于在数据库中插入值 [英] About insert value in database

查看:78
本文介绍了关于在数据库中插入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

推荐答案

调用ExecuteNonQuery()方法的SqlCommand只有1m而你声明它2.



The SqlCommand calling the ExecuteNonQuery() method only has 1 "m" while you declared it with 2.

com.ExecuteNonQuery() should be comm.ExecuteNonQuery()





另外,我会在你的其他代码所在的范围内声明你的SqlConnection。



Also, I would declare your SqlConnection in the same scope your other code is in.


你的INSERT语句缺少列的名称。最佳做法是包含列的名称,以便在以后有人将一个或多个列添加到数据库表时,SQL语句将起作用。



Your INSERT statement is missing the names of the columns. Best practice is to include the names of the columns so that your SQL statements will work should someone later add one or more columns to the database table.

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);



阅读本文:使用SQL参数克服特殊性能问题 [ ^ ]


这篇关于关于在数据库中插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆