我不知道这段代码中的错误是什么 [英] I don't know what is errore in this code

查看:70
本文介绍了我不知道这段代码中的错误是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace TestCon
{
    public partial class index : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
            con.Open();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into tbl_user values('"+TextName.Text+"','"+TextAdd.Text+"','"+TextDate.Text+"')",con);
            cmd.ExecuteNonQuery();
            con.Close();
            LabSave.Visible = true;
            LabSave.Text = "Data Save";
            TextName.Text = "";
            TextAdd.Text = "";
            TextDate.Text = "";





我尝试了什么:



在此句子中运行Web应用程序时给出错误



What I have tried:

give me error when run web application in this Sentences

cmd.ExecuteNonQuery();
           con.Close();

推荐答案

0)页面加载时不要打开数据库连接。等到你确实需要打开它之前这样做。



1)使用参数化查询来避免SQL注入攻击



更好的代码:



0) Do NOT open your db connection when the page loads. Wait until you actually need it to be open before doing so.

1) Use parameterized queries to avoid SQL injection attacks

Better code:

SqlConnection con = null;
SqlCommand cmd = null;
try
{
    using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"]))
    {
        con.Open();
        string query = "insert into tbl_user (column1, column2, ...) values (@col1, @col2, ...)";
        SqlParameter[] parameters = new SqlParameter[]
        {
            new SqlParameter("@col1", col1Value),
            new SqlParameter("@col2", col2Value),
            ...
        };
        using (cmd = new SqlCommand(query, con))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddRange(parameters);
            cmd.ExecuteNonQuery();
        }
    }
}
catch (Exception ex)
{
    // do something with exception
}

参见解决方案1.



我提出了类似的解决方案:

See Solution 1.

I came up with a similar solution :
using SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString)
{
	con.Open();
	SqlCommand cmd = new SqlCommand("insert into tbl_user values(@name, @add, @date)",con);
	cmd.Parameters.AddWithValue("@name", TextName.Text);
	cmd.Parameters.AddWithValue("@add", TextAdd.Text);
	cmd.Parameters.AddWithValue("@date", TextDate.Text);
	cmd.ExecuteNonQuery();
	// rest of your code 
	// ...
	
}//This closes the using and therefore closes your connection and properly disposes of it

请注意最后的注释...有关详细信息,请参阅< a href =https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement>使用Statement(C#参考)| Microsoft Docs [ ^ ]



如果在使用参数后仍然出现错误,请检查 TextDate.Text的内容 - 你真的可以约会吗?您可能需要考虑进行一些确认它是有效日期的验证。

Note the comment at the very end ... for more information see using Statement (C# Reference) | Microsoft Docs[^]

If you still get an error after using Parameters then check the contents of your TextDate.Text - can you actually make a date of that. You might want to consider putting some validation in place that ensures it is a valid date.


Quote:

在这句话中运行Web应用程序时给出错误

give me error when run web application in this Sentences



提供错误文本是个好主意,因为它告诉错误是什么。




It is a good idea to give the text of error as it tells what is the error.

SqlCommand cmd = new SqlCommand("insert into tbl_user values('"+TextName.Text+"','"+TextAdd.Text+"','"+TextDate.Text+"')",con);



不是你问题的解决方案,而是你遇到的另一个问题。

永远不要通过连接字符串来构建SQL查询。迟早,您将使用用户输入来执行此操作,这会打开一个名为SQL注入的漏洞,这对您的数据库很容易并且容易出错。

名称中的单引号你的程序崩溃。如果用户输入像Brian O'Conner这样的名称可能会使您的应用程序崩溃,那么这是一个SQL注入漏洞,崩溃是最少的问题,恶意用户输入,并且它被提升为具有所有凭据的SQL命令。

SQL注入 - 维基百科 [ ^ ]

SQL注入 [ ^ ]

按示例进行SQL注入攻击 [ ^ ]

PHP:SQL注入 - 手册 [ ^ ]

SQL注入预防备忘单 - OWASP [ ^ ]

我该怎么办?解释没有技术术语的SQL注入? - 信息安全堆栈交换 [ ^ ]


Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]


这篇关于我不知道这段代码中的错误是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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