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.
Related
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to add data to my access database from winform using c#.
I keep getting a syntax error regarding my INSERT INTO statement and cannot see where I am going wrong.
Please can someone review my code and tell me where I am going wrong.
private void btnLog_Click(object sender, EventArgs e)
{
txtStatus.Text = "Open";
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\mwool\\Desktop\\Uni\\3rd Year\\SEM 1\\AP\\Assignment\\Staff.accdb";
string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES ('" + txtFaultType.Text + "', '" + txtStatus.Text + "', " + txtTechId.Text + "' , '" + txtStaffId.Text + "' , '" + txtZone.Text + "' , '" + txtDescription.Text + "')";
OleDbCommand add = new OleDbCommand();
add.CommandText = sql;
add.Connection = conn;
add.Connection.Open();
add.ExecuteNonQuery();
conn.Close();
}
You missed a single quote before txtTechId.Text. However you should always use parameterized queries to avoid SQL Injection.
string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES (#a,#b,#c,#d,#e,#f)";
add.Parameters.AddWithValue("#a", txtFaultType.Text);
add.Parameters.AddWithValue("#b", txtStatus.Text);
add.Parameters.AddWithValue("#c", txtTechId.Text);
add.Parameters.AddWithValue("#d", txtStaffId.Text);
add.Parameters.AddWithValue("#e", txtZone.Text);
add.Parameters.AddWithValue("#f", txtDescription.Text);
Always use parameterized queries. This prevents simple mistakes like forgetting a ' with a string but more importantly prevents sql injection attacks.
Also always wrap your database connections, commands, and any other Disposable objects in using blocks.
Your code refactored with using statements and parameterized inputs.
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\mwool\\Desktop\\Uni\\3rd Year\\SEM 1\\AP\\Assignment\\Staff.accdb"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, [Description]) VALUES (?, ?, ?, ?, ?, ?)";
cmd.Parameters.Add(new OleDbParameter("#faultType", OleDbType.VarChar)).Value = txtFaultType.Text;
cmd.Parameters.Add(new OleDbParameter("#Status", OleDbType.VarChar)).Value = txtStatus.Text;
// this parameter is an example of passing an int instead of a string. Alwaysuse the correct types!
cmd.Parameters.Add(new OleDbParameter("#TechId", OleDbType.Int)).Value = int.Parse(txtTechId.Text);
cmd.Parameters.Add(new OleDbParameter("#StaffId", OleDbType.VarChar)).Value = txtStaffId.Text;
cmd.Parameters.Add(new OleDbParameter("#Zone", OleDbType.VarChar)).Value = txtZone.Text;
cmd.Parameters.Add(new OleDbParameter("#Description", OleDbType.VarChar)).Value = txtDescription.Text;
con.Open();
cmd.ExecuteNonQuery();
}
OleDbCommand does not support named parameters, see OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
Also note that:
OleConnection and OleDbCommand are wrapped in using blocks so they are disposed/cleaned up even when an exception occurs.
Parameters are now used instead of hard coding the string values
Parameters use the correct data types
It might be that the use of Description is not allowed because it is a reserved word (see link). In that case surround it with [] (see update above).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am relatively new to c# and I am practicing adding databases to store my information. I cannot get the connection string to work for me. the code is :
SqlConnection con = new SqlConnection("Data Source = (LocalDB)/MSSQLLocalDB; AttachDbFilename='C:/Users/joeco_000/Documents/Visual Studio 2015/Projects/Telephone project/Telephone project/Database1.mdf';Integrated Security = True'");
I then have a button that will add the information to the database that is:
private void button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#" INSERT INTO Phon table (First,last,email,mobile,catagory) VALUES ('" + textBox2.Text + "' , '" + textBox3.Text + "' , '" + textBox4.Text + "' , '" + textBox5.Text + "','" + comboBox1.Text + "')");
cmd.ExecuteNonQuery();
con.Close();
I have taken this information from a tutorial that is 6 years old. Any help would be amazing.
You haven't associated the command with the connection before attempting to execute the query. One way to do this is:
SqlCommand cmd = new SqlCommand(sql, connection)
Another way is:
cmd.Connection = con;
The name Phon table is not a valid table name. If your table really has a space in its name you need to surround it with square braces
INSERT INTO [Phon table] (First,last,email.......
Note that this is in addition to associating your command with your connection as the other answer indicates.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following query in c# and don't have any idea why it shows me this error:
"syntax error on INSERT INTO statement".
I use Access 2013.
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO money (price,cardnum,checknum,dateTime,employeeid) values('" + TempPrice + "','" + TempCriditNum + "','" + TempCheckNum + "','" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "','" + id + "')";
command2.ExecuteNonQuery();
connection.Close();
A few things to check
dateTime is a reserved word. Try wrapping it in square brackets -
if the type of data you are dealing with is a Date\Time then you should be wrapping the input in # signs
if your data types are not strings, do not wrap them in quotes
as pointed out by Jia Jian, you should use parameterized queries
as pointed out by HansUp, Money is also a reserved word, so wrap it in square brackets
So the query ends up looking like :
command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";
Your SQL statement might be prone to SQL injection. Consider using parameterized queries by adding values via the OleDbCommand.Parameters property instead of concatenating it.
An example would be:
command2.CommandText = "INSERT INTO [money] (price, cardnum, checknum, [dateTime], employeeid) values(#tempPrice, #tempCreditNum, #tempCheckNum, #dateTime, #id)";
command2.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("#tempPrice", TempPrice),
new OleDbParameter("#tempCreditNum", TempCriditNum),
new OleDbParameter("#tempCheckNum", TempCheckNum),
new OleDbParameter("#dateTime", dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString()),
new OleDbParameter("#id", id)
});
command2.ExecuteNonQuery();
This should also solve your syntax error.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Why does this code throw an error?
using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
{
MySqlCommand Command = new MySqlCommand();
Command.Connection = cn;
Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
"') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
DateTime.Today.ToString("yyyy-MM-dd") + "";
cn.Open();
Command.ExecuteNonQuery();
//Ryd op
Command.Dispose();
cn.Close();
}
}
Rather than just forgetting ' for the value of Brugernavn column and both single quotes for Dato column, I think you have more things to keep in mind.
Use using statement to dispose your Command object as you did for your connection instead of calling Close or Dispose methods manually.
Use paramterized queries instead of string concatenation. This kind of codes are open for SQL Injection attacks.
Looks like you try to save your DateTime values with their string representations. Do not do that! If you wanna keep your DateTime values to your database, you need to pass them directly. Change your Dato column to DateTime type. Read: Bad habits to kick : choosing the wrong data type
using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
Command.CommandText = #"UPDATE TeleworksStats SET Ja = #Ja
WHERE Brugernavn = #Brugernavn AND Dato = #Dato";
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = JaTak;
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
Command.Parameters.Add("#Ja", MySqlDbType.DateTime).Value = DateTime.Today;
// I assumed your column types. You should write proper column types instead.
cn.Open();
Command.ExecuteNonQuery();
}
You missed one quote ' after Brugernavn = and Dato:
Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
DateTime.Today.ToString("yyyy-MM-dd") + "'";
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection like this:
Command.CommandText =
"UPDATE TeleworksStats SET Ja = #Ja WHERE Brugernavn = #Brugernavn and ...";
Command.Parameters.AddWithValue("#Ja", JaTak);
Command.Parameters.AddWithValue("#Brugernavn", VarribleKeeper.Brugernavn);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?