如何插入 table asp.net C#

How to insert into table asp.net C#

我正在尝试将注册页面中的值插入 table login_tbl:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);

conn.Open();

string insertQ = "INSERT INTO login_tbl (empid,first_name,last_name,team_name,pwd,email_id,extension) VALUES('" + empbox.Text + "','" + fnamebox.Text + "','" + lnamebox.Text + "','" + teamnamebox.SelectedItem.Text + "','" + passwordbox.Text + "','" + emailbox.Text + "','" + extensionbox.Text + "')";

SqlCommand com = new SqlCommand(insertQ, conn);

com.ExecuteNonQuery();
Response.Write("registration done");

我在 com.ExecuteNonQuery();" 行遇到错误。它会进入异常状态

error:System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlExcep‌​tion exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(Tds‌​ParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,

我认为您在这里缺少添加参数,我想知道您为什么不添加这样的值:

VALUES(@param1,@param2,@param3)";

我觉得这样加比较简单?

试试这个:

using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
     connection.Open();

    string insertQ = "INSERT INTO login_tbl (empid,first_name,last_name,team_name,pwd,email_id,extension) VALUES(@param1,@param2,@param3,@param4,@param5,@param6,@param7)";

        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.Parameters.Add("@param1", SqlDbType.Int).value = empid;
        cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value=first_name;
        cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value=last_name;
        cmd.Parameters.Add("@param4", SqlDbType.Varchar, 50).value = team_name;
        cmd.Parameters.Add("@param5", SqlDbType.Varchar, 50).value = pwd;
        cmd.Parameters.Add("@param6", SqlDbType.Int).value = email_id;
        cmd.Parameters.Add("@param7", SqlDbType.Varchar, 50).value = extension;
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
}
Response.Write("registration done");

其中一个值太长。您将需要对防止异常发生所需的值进行服务器端验证。从各个方面(包括但不限于长度)检查您要保存的所有字段是否有效。如果它们恰好无效,则向客户端发送有意义的错误消息并在那里处理问题。现在,当您修复了异常的原因后,对于可以在客户端确定有效性的所有情况,请确保首先不会将无效输入从浏览器发送到服务器,这将减少服务器负载释放所有无效请求的负担。

现在,当您进行验证时,您还需要考虑其他方面。您的代码也容易受到 SQL injection. You might either escape the values and handle them properly yourself, or use something which will do that for you, like parameterized queries. Since you have SQL injection vulnerability, it is safe to assume you have an XSS 注入漏洞的攻击。如果你有它,请确保你也修复它。