System.Data中发生了类型为“System.Data.SqlClient.SqlException”的异常.dl

本文关键字:System Data 异常 dl SqlException 发生了 类型 SqlClient | 更新日期: 2023-09-27 18:36:14

我是C#新手

当我在应用程序运行时按下提交按钮时,我收到错误"系统数据中发生了'系统数据.SqlClient.SqlException'类型的异常.dll但未在用户代码中处理"

这是我的代码,我收到错误

public partial class About : Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Table values('" + txtName.Text + "','" + txtPrice.Text + "','" + txtQuan.Text + "','" + txtURL.Text + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();
        Label1.Visible = true;
        Label1.Text = "Your Data Stored Succesfully!";
        txtName.Text = "";
        txtPrice.Text = "";
        txtQuan.Text = "";
        txtURL.Text = "";
    }    

System.Data中发生了类型为“System.Data.SqlClient.SqlException”的异常.dl

您的代码存在多个问题。最明显的是,正如您的错误消息所暗示的那样,您没有捕获异常,您没有任何错误处理。通常,数据库,网络,文件IO和其他类似外部的东西需要错误处理。您应该使用与使用它相同的方法打开连接并关闭它,最好是在 using 块内。最重要的是,您的代码容易受到 SQL 注入的影响。您需要了解数据库的第一件事是使用参数,并且不要在SQL中连接字符串。