简体   繁体   中英

Inserting data into SQL table from asp.net form

I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:

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();
    }
}

The error occurs in my GetConnection() method where I return the connection. The error I get is:

An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code

Additional information: Format of the initialization string does not conform to specification starting at index 0.

I do not know how to get past this problem but any help is very appreciated.

Your problem lies in

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

your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.

Standard Connection with username and password:

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

Trusted Connection:

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

You might want to look at this question for example: How to set SQL Server connection string?

Pijemcolu 's answer is correct, but I think several things can be added to enhance your code:

1) use proper names for variables. Eg: connection string is different from actual connection

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) Try to dispose disposable objects (ie implement IDisposable ) should be properly disposed.

Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here ).

The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).

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) Password storage

It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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