Reputation: 17
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
String uname, pass;
uname = textBox1.Text;
pass = textBox2.Text;
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
String query = "insert into LOGIN_TABLE (UserName, Password) VALUES ('" +
textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "') ";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
OleDbParameter myParm = myCommand.Parameters.Add("@uname", OleDbType.VarChar, 50);
myParm.Value = textBox1.Text;
myParm = myCommand.Parameters.Add("@pass", OleDbType.VarChar, 50);
myParm.Value = textBox2.Text;
myCommand.ExecuteNonQuery();
myConnection.Close();
Upvotes: 0
Views: 4542
Reputation: 107536
You haven't told your OleDbCommand
which database connection to use.
Try doing this instead:
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
And then don't set the CommandText
property on the next line.
Update: Marc was right, you weren't even using your parameters because your query definition didn't lend itself to what's called a Prepared Statement. Try this:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
using (OleDbConnection myConnection = new OleDbConnection(connectionString))
{
myConnection.Open();
string query = "INSERT INTO LOGIN_TABLE (UserName, Password) VALUES (?, ?)";
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
myCommand.Parameters.Add("UserName", OleDbType.VarChar, 50);
myCommand.Parameters.Add("Password", OleDbType.VarChar, 50);
myCommand.Parameters[0].Value = textBox1.Text;
myCommand.Parameters[1].Value = textBox2.Text;
myCommand.Prepare();
myCommand.ExecuteNonQuery();
}
I got rid of some unnecessary assignments and set up your command parameters a little differently. Give it a shot and let me know if that solves your problem.
Upvotes: 3