3

i am trying to insert data from a form to msaccess database i have the current code

OleDbConnection con = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
con.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\kunz\Documents\Visual Studio 2010\WebSites\Assignment_2_Mark_2\App_Data\nuclearpopsicledb.mdb";
cmd.Connection = con;
string sql = "insert into users values('"+tbUname.Text+"','"+tbPass.Text+"','"+tbName.Text+"','"+tbEmail.Text+"','"+tbEmail.Text+"')";

try
{
    con.Open();
    cmd.CommandText = sql;
    cmd.ExecuteNonQuery();
    con.Close();
    Label1.Text = "TRY";
}
catch(Exception ex)
{
    Label1.Text = ex.ToString();
    con.Close();
}

my data base is structured like:

|username | password | name | email |

but when ever i run it i get an error like

System.Data.OleDb.OleDbException: Number of query values and destination fields are not the same. at System.Data.

i am not sure what i am doing wrong i am a beginner in C#

2
  • 1
    Your objects that implement IDisposable such as OleDbConnection are not being handled properly. Wrap them in a using statement. Commented Apr 25, 2017 at 14:59
  • 1
    I understand this is probably a learning assignment, but you are storing plaintext passwords in the database. This is a big security violation. Passwords should be one way hashed and encrypted, never stored in plaintext. Commented Apr 25, 2017 at 14:59

2 Answers 2

3

You have an extra email you are passing:

cmd.Parameters.AddWithValue("@userName", tbUname.Text.Trim());
cmd.Parameters.AddWithValue("@password", tbPass.Text.Trim());
cmd.Parameters.AddWithValue("@Name", tbName.Text.Trim());
cmd.Parameters.AddWithValue("@Email", tbEmail.Text.Trim());

string sql = 
    "insert into users " +
    "values(@userName, @password, @Name, @Email)";
Sign up to request clarification or add additional context in comments.

4 Comments

is this the best way to do it is there a better way like to prevent sql injections
@GibralterTop Then show how to do parameters. Don't show how to do things the incorrect way.
Parameters are great for preventing sql injection. But you also need to hash that pass.
Else you or some malicious user might feel a little curious one day and try out some email password combinations on facebook, amazon, bank of america, etc
1

Actually your table contains four values, but you are passing 5 values in that query. That is the mistake.

Your Code:

string sql = "insert into users values('"+tbUname.Text+"','"+tbPass.Text+"','"+tbName.Text+"','"+tbEmail.Text+"','"+tbEmail.Text+"')";

tbEmail.Text is repeating Twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.