【问题标题】:Inserting data into SQL table from asp.net form从asp.net表单将数据插入SQL表
【发布时间】:2016-03-07 16:08:15
【问题描述】:

我正在尝试构建一个注册 Web 表单,将用户数据保存到 SQL 表中。这是我到目前为止所拥有的:

public static SqlConnection GetConnection()
{
    String connection;
    connection = @"example/file/path";

    return new SqlConnection(connection);

}
protected void submitButton_Click(object sender, EventArgs e)
{
    SqlConnection myConnection = GetConnection();

    try
    {

        myConnection.Open();
        String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
            +fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
            + dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";

        SqlCommand myCommand = new SqlCommand(myQuery, GetConnection()); 
        myCommand.ExecuteNonQuery();
        myConnection.Close();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        myConnection.Close();
    }
}

错误发生在我返回连接的GetConnection() 方法中。我得到的错误是:

“System.ArgumentException”类型的异常发生在 System.Data.dll 但未在用户代码中处理

附加信息:初始化字符串的格式不符合从索引 0 开始的规范。

我不知道如何解决这个问题,但非常感谢任何帮助。

【问题讨论】:

  • connection = @"example/file/path"; ??
  • 你有一个很棒的 SQL 注入漏洞,使用参数化查询
  • 你将不得不提供一个真正的连接字符串 - 见这里connectionstrings.com
  • @JSantosh 这不是我真正的连接字符串

标签: c# asp.net sql-server


【解决方案1】:

你的问题出在

String connection;
connection = @"example/file/path";
return new SqlConnection(connection);

您的 connectionString 变量(在您的情况下为连接)设置不正确,有多种方法可以做到这一点,仅列出 2 个最常见的。

带有用户名和密码的标准连接:

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

可信连接:

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();

您可能想看看这个问题,例如: How to set SQL Server connection string?

【讨论】:

    【解决方案2】:

    Pijemcolu 的回答是正确的,但我认为可以添加一些东西来增强您的代码:

    1) 为变量使用正确的名称。 例如:连接字符串与实际连接不同

    public static SqlConnection GetConnection()
    {
        // if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
        String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
        return new SqlConnection(connStr);
    
    }
    

    2) 尝试处置一次性物品(即实现IDisposable)应妥善处置。

    此外,命令不应使用字符串连接构造,而应使用参数。这在向查询提供直接用户输入时尤为重要,因为恶意用户可能会尝试执行查询以破坏数据(阅读更多关于 SQL 注入的信息here)。

    连接只能在finally 块内关闭,因为无论如何都会执行那里的所有内容(catch 块中是否引发异常)。

    protected void submitButton_Click(object sender, EventArgs e)
    {
        SqlConnection myConnection = null;
        try
        {
            using (myConnection = GetConnection())
            {
                myConnection.Open();
                String myQuery = @"
                    INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) 
                    values (@firstName, @lastName, @eMail, @dob, @userName, @password)";
    
                using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
                { 
                    myCommand.Parameters.AddWithValue("@firstName", fNameBox.Text);
                    myCommand.Parameters.AddWithValue("@lastName", lNameBox.Text);
                    myCommand.Parameters.AddWithValue("@eMail", emailBox.Text);
                    myCommand.Parameters.AddWithValue("@dob", dobBox.Text);
                    myCommand.Parameters.AddWithValue("@userName", userNameBox.Text);
                    myCommand.Parameters.AddWithValue("@password", passwordBox.Text);
    
                    myCommand.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            if (myConnection != null)
                myConnection.Close();
        }
    }
    

    3) 密码存储

    看起来您的存储密码是用户输入的。强烈建议存储密码的表示形式(某种哈希值,很容易从字符串中计算出来,但几乎不可能从哈希值中检索到字符串)。更多详情请见here

    【讨论】:

    • 感谢您的帮助,但 myCommand 方法出现错误。它说它在当前上下文中不存在。我该怎么办?
    • @Reggie - 抱歉,它已超出其范围。我已将答案编辑到适当的位置。
    猜你喜欢
    • 2013-06-21
    • 1970-01-01
    • 2011-06-13
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多