Reputation: 9
I'm new to C#, only been studying it for a few weeks. I'm writing an application with a windows form from and Access database at the back. I want the details inserted by the user to be added to access database. I've looked through other forums (including on stackoverflow) to get this far, but I keep getting an error thrown at run time stating 'Command text was not set for the command object' (ive highlighted the line it appears on below) which I dont understand and can't get rid of. Any help would be much appreciated. Thanks K
private void btnOkay_Click(object sender, EventArgs e)
{
string connectionString =
"provider=Microsoft.ACE.Oledb.12.0;" +
"data source=C:\\Users\\Documents\\StudentRegistrationDatabase.accdb";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
string strSql = @"INSERT INTO StudentDetails ([Forename],[Surname],[CourseName],[DOB],)" +
"VALUES('"+txtFirstName.Text +"','" +txtLastName.Text +"','" +txtCourseName.Text +"','"+ txtDOB.Text +"')";
myOleDbConnection.Open();
OleDbCommand cmd = new OleDbCommand(strSql, myOleDbConnection);
cmd.Parameters.AddWithValue("@Forename", txtFirstName);
cmd.Parameters.AddWithValue("@Surname", txtLastName);
cmd.Parameters.AddWithValue("@CourseName", txtCourseName);
cmd.Parameters.AddWithValue("@DOB", txtDOB);
**myOleDbCommand.ExecuteNonQuery();** }
Edit: Thank you all for your replies. When I first started coding this piece, I used the following lines of code:
' {
string connectionString =
"provider=Microsoft.ACE.Oledb.12.0;" +
"data source=C:\\Users\\Botterill\\Documents\\StudentRegistrationDatabase.accdb";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbConnection.Open();
myOleDbCommand.CommandText = "INSERT INTO StudentDetails ([Forename],[Surname],[CourseName],[DOB],)" +
"VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtCourseName.Text + "','" + txtDOB.Text + "')";'
**myOleDbCommand.ExecuteNonQuery();**
But, on the line in bold I was getting a runtime error saying that there was 'Syntax error in INSERT INTO statement'.I thought this would be corrected in the changes I made in the first question I posted. Any help would be appreciated greatly. Thanks Kate
Upvotes: 1
Views: 2365
Reputation: 14591
You create myOleDbCommand
from the connection and then you continue to set up the cmd
instance with the query text, and then you execute myOleDbCommand
which doesn't have any command text attached to it.
Which instance of OleDbCommand
do you really want to use?
Additionally, as @thorarin notes, you should use the named parameters (as in cmd
example) and not concatenate the strings to create the command text, as you open your application for SQL injection attacks.
Upvotes: 3