This question already has answers here:
OleDbCommand parameters order and priority
(3 answers)
Is order of parameters for database Command object really important?
(3 answers)
OleDbParameters and Parameter Names
(2 answers)
Closed 4 years ago.
I have an access database with my work that I am trying to insert into but I keep getting.
'You cannot add or change a record because a related record is required in table 'Projects'.'
I'm running this query: INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)
On this Structure: picture of database structure in access
With this code in C# with an OleDb... commands and connections Which are working fine for other query's:
private void addTaskBTN_Click(object sender, EventArgs e)
{
//the assign id is already known and is of type integer.
string query = "SELECT Project_ID FROM Projects WHERE Project_Name = #project";
OleDbConnection con = new OleDbConnection(con_string);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#project", projectComboBox.Text);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
project_id = Convert.ToInt16(reader[0]);
Console.WriteLine(project_id);
}
con.Close();
Console.WriteLine("submit: " + project_id + " " + employee_id + " " + descriptionTextBox.Text + " " + monthCalendar1.SelectionStart);
Console.WriteLine(monthCalendar1.SelectionStart);
query = "INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)";
con = new OleDbConnection(con_string);
cmd = new OleDbCommand(query, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#project", project_id);
cmd.Parameters.AddWithValue("#assign", employee_id);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text.ToString());
//cmd.Parameters.AddWithValue("#deadline", monthCalendar1.SelectionStart);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.Close();
}
I have tried looking at other examples of this problem and I don't understand why I'm getting this error. #project has a valid id number of the primary key for a Project, #assign has a valid employee id as well and #description is string of text. Thanks for any help.
Steve correctly identified the mistake you have to put your parameters in the right order. My fix was to arrange my parameters in order.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I am using the following code to add items to the table but I have troubles deleting or updating items in the table. I am trying commands like
delete from MyTable
values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
and the command is accepted but the item is not deleted.
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into MyTable values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item inserted");
It is a bit hard to find resources since google just shows, sql or mysql when I try to search for a solution.
Why would you expect an SQL command based on the INSERT keyword to delete a record?
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
DELETE
FROM MyTable
WHERE MyColumn= #SomeValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
Pay special attention to how I used a query parameter. The string concatenation technique in the question is NEVER okay, and is the easiest way I've seen to find out a year from now you were hacked six months ago.
To change (update) a record, you must write an UPDATE query:
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
UPDATE MyTable
Set SomeColumn = #SomeValue
WHERE SomeOtherColumn = #SomeOtherValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox2.Text;
cmd.Parameters.Add("#SomeOtherValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
The thing to understand about this is you do not delete or update a record by specifying all the fields in a VALUES() clause, as you would with an INSERT. Instead, you use a WHERE clause and only need to include enough for the conditional expressions to identify which row(s) you want to change or delete. An UPDATE statement will then further specify what to change via the SET clause.
This question already has answers here:
What are good ways to prevent SQL injection? [duplicate]
(4 answers)
Closed 3 years ago.
I am currently building my first web app from scratch and trying to figure out the communication of C# and SQLDatabases, I've been trying to enter custom data into a table.
This code for some reason works perfectly fine, and it successfully adds "Id = 3" in a new row:
sql = " INSERT INTO dbo.AspNetUsers (Id) VALUES (3)";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
But this one does not, and the only difference is that it adds another item in a different column, as opposed to the previous one which it only adds the "Id":
sql = " INSERT INTO dbo.AspNetUsers (Id, UserName) VALUES (3, testName)";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
Lastly, another problem I have, I am unable to use either ExecuteReader() and ExecuteScalar() to read data from tables created by me as opposed the ones set up by the Framework auth system.
Thanks in advance.
This code addresses both issues:
the value of UserName is passed as a SQL parameter, which is recommended for string values to avoid SQL injection and other possible problems,
the SQL command is executed with ExecuteNonQuery, the correct way of calling SQL commands that do not return any result
SqlCommand cmd = new SqlCommand();
string sql = " INSERT INTO dbo.AspNetUsers (Id, UserName) VALUES (3, #testName)";
cmd.Parameters.AddWithValue("#testName", "testName");
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
This question already has answers here:
How can I add user-supplied input to an SQL statement?
(2 answers)
Closed 4 years ago.
I'm facing a problem with decrementing value with MS Access database.
I get an error
Syntax error in UPDATE Statement
My code:
connection.Open();
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " update Cards set Count = Count - 1 where Type=" + ct + " ";
command.ExecuteNonQuery();
connection.Close();
Can anyone please help?
You should provide an actual error.
My guess is that count is a keyword and has to be put in square brackets like so [count]
and do use parameters, see Joel's answer
It's not certain, but I strongly suspect it's missing single quotes around ct. Fix it like this:
using (var connection = new OleDbConnection("connection string here"))
using (var command = new OleDbCommand("update Cards set Count = Count - 1 where Type= ?", connection))
{
//have to guess at the OleDbType value. Use the actual column type and length from the database
cmd.Parameters.Add("?", OleDbType.VarWChar, 10).Value = ct;
connection.Open();
command.ExecuteNonQuery();
}
There are several other important fixes in this pattern, too.
This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 7 years ago.
I keep getting this error saying that "ExecuteScalar has not been initialized" I have new to C# but had a look through google and tutorials and still cant see what the problem is. Its probably a very silly mistake but if anyone could help. Thanks :)
// open connection
myConnection.Open();
// sql command
string Account_Num = txt_acc.Text;
string Pin_num = txt_pin.Text;
SqlCommand check_details = new SqlCommand("select Account_num, Pin_num from Cust_details where Account_num='" + txt_acc.Text + "'and Pin_num ='" + txt_pin.Text + "'");
check_details.Parameters.AddWithValue("#Account_num", txt_acc.Text);
check_details.Parameters.AddWithValue("#Pin_num", txt_pin.Text);
int result = Convert.ToInt32(check_details.ExecuteScalar());
if (result > 0)
{
Console.WriteLine("user exists");
}
else
{
Console.WriteLine("error");
}
}
Looks like you didn't connect your command with connection. Just set it's Connection property to myConnection.
check_details.Connection = myConnection;
or you can set it on your SqlCommand constructor as a second parameter;
SqlCommand check_details = new SqlCommand("yourCommand", myConnection);
or you can use CreateCommand method from your connection;
SqlCommand check_details = myConnection.CreateCommand();
And you are misunderstood the parameterized queries. You still do string concatenation in your sql query but you try to add parameters. That's meaningless.
Use using statement to dispose your connection and command automatically as well.
Also don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
using(var myConnection = new SqlConnection(conString))
using(var check_details = myConnection.CreateCommand())
{
check_details.CommandText = #"select Account_num, Pin_num from Cust_details
where Account_num = #accnum
and Pin_num = #pinnum";
// I assume your column types as Int
check_details.Parameters.Add("#accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex);
check_details.Parameters.Add("#pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text);
myConnection.Open();
int result = (int)check_details.ExecuteScalar();
...
}
By the way, there is no point to select Pin_num column in your command since ExecuteScalar ignores it.
I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements