简体   繁体   English

查询数据库时出现SqlException

[英]SqlException when querying database

when I developing just registration page this error occurred 当我开发仅注册页面时,发生此错误

error:An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code 错误:System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理

code

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;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            String checkuser = "select count(*) from [UserData] where User Name='"+ TextBox1UN.Text +"'";
            SqlCommand comm = new SqlCommand(checkuser,conn);
             int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
            if(temp==1)
            {
                Response.Write("user allready exists");

            }

         conn.Close();

        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
            {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            String InserQuery = "insert into [UserData](UserName,Email,Password,Country)values(@Uname,@email,@pass,@country)";
            SqlCommand comm = new SqlCommand(InserQuery, conn);
            comm.Parameters.AddWithValue("@Uname", TextBox1UN.Text);
            comm.Parameters.AddWithValue("@email", TextBox2EI);
            comm.Parameters.AddWithValue("@pass", TextBox3PW);
            comm.Parameters.AddWithValue("@country", DropDownList1cont.SelectedItem.ToString());
            comm.ExecuteNonQuery();
            Response.Write("Registration is succesful");
            Response.Write("Administrator.aspx");

            conn.Close();
        }
        catch (SqlException ex)
        {
            Response.Write("Error:"+ex.ToString());
        }
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }
}

aspx file: aspx文件:

<asp:SqlDataSource ID="SqlDataSourceRegistration" 
       runat="server" 
       ConnectionString="<%$ConnectionStrings:RegistrationConnectionString %>"
       OnSelecting="SqlDataSourceRegistration_Selecting" 
       SelectCommand="SELECT * FROM [UserData]" >
</asp:SqlDataSource>

Your Query is not valid there is space between User Name and User is a keyword in sql . 您的Query无效, User NameUsersql的关键字之间没有space Your query should look like this 您的查询应如下所示

"select count(*) from [UserData] where UserName=@username";

Use Parameterized SQL 使用参数化SQL

Add parameters to the command instead of concatenating values command添加parameters ,而不是concatenating

comm.Parameters.AddWithValue("@username",TextBox1UN.Text);

A tip: Your code is very hackable / unsecure... because you put user input into the sql string you should use parameters instead. 提示:您的代码很容易被入侵/不安全...因为您将用户输入放入sql字符串中,因此应该使用参数。

You also have a space in your field name 'User Name' which I'm guessing is your issue so I put it as 'UserName'. 您在字段名称“用户名”中也有一个空格,我猜这是您的问题,因此我将其命名为“用户名”。

You should also put your code into a try catch statement so you can read the error. 您还应该将代码放入try catch语句中,以便读取错误。

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

    using (SqlCommand command = new SqlCommand(
        "SELECT COUNT(*) from [UserData] where UserName= @Name", connection))
    {
        // Add new SqlParameter to the command.
        command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = TextBox1UN.Text;

        int temp = Convert.ToInt32(command.ExecuteScalar().ToString());

        if(temp==1)
        {
            Response.Write("user allready exists");
        }
    }
}
catch (Exception ex)
{
    // Display the exception's data dictionary.
    foreach (DictionaryEntry pair in ex.Data)
    {
        Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM