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).
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.
Storing Japanese characters from a form TextBox to SQL table appears as question marks.
I'm just trying to make a table that holds the Japanese text and the English translation to make my life easier as I'm studying Japanese.
Searching for a solution 2 days now nothing seems to be working.
I am not even sure if this is actually a good practice for storing text to data table.
Also column where I want the Japanese character stored is set to nvarchar(50).
private void addWordButton_Click(object sender, EventArgs e)
{
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT Words (WordJapanese, WordEnglish) VALUES ('" + newJPwordTxt.Text + "', '" +
newENwordTxt.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
It seems you have missed the into keyword in your Insert statement, as a second note, you need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack. You should always use parameterized queries to avoid SQL Injection:
cmd.CommandText = "INSERT into Words (WordJapanese, WordEnglish) VALUES (#WordJapanese, #WordEnglish)";
cmd.Parameters.Add("#WordJapanese", SqlDbType.NVarChar, 50).Value = newJPwordTxt.Text;
cmd.Parameters.Add("#WordEnglish", SqlDbType.NVarChar, 50).Value = newENwordTxt.Text;
Your query has syntax issues and secondly you should be using parameterized queries to safeguard from SQL Injection.
The following should be good :
cmd.CommandText = "INSERT INTO Words(WordJapanese, WordEnglish) VALUES (#Japanse, #English)";
cmd.Parameters.Add("#Japanse", SqlDbType.NVarChar, 50).Value = newJPwordTxt.Text;
cmd.Parameters.Add("#English", SqlDbType.NVarChar, 50).Value = newENwordTxt.Text;
I have this INSERT statement,
"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
$"VALUES ('{name}','{email}','{address}')";
So as you can see on the 2nd line, i have added '$'. This version of the code works, but it's not supported in VS2012.
I'm trying to convert this into something like this but I'm having a lot of issues since it's so very complicated .
"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (''" + name + "', ''" + email + "', ''" + address + "')";
This version above doesn't work. Basically i'm trying to make a query without using the '$' Any ideas?
Don't do that at all, it exposes you to SQL injection attacks and converions issues. What would a date look like if you tried to pass it using string concatenation? A decimal?
It's actually easier to use parameterized queries :
//Create a SqlCommand that can be reused
SqlCommand _cmdInsert;
var sql="INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (#name,#email,#address)";
var cmd=new SqlCommand(cmd);
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 30);
cmd.Parameters.Add("#email", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 50);
_cmdInsert=cmd;
Later, you can use the command directly by setting a connection and parameter values :
using(var connection=new SqlConnection(theConnectionString)
{
_cmdInsert.Connection=connection;
_cmdInsert.Parameters["#name"].Value=someName;
...
connection.Open();
_cmdInsert.ExecuteNonQuery();
}
Parameterized queries pass the strongly-typed values alongside the query in the RPC call. A DateTime is passed as a DateTime (or the binary equivalent) to the server, not as a string. This way, there are no conversion errors. No matter what the value contains, it's never mixed with the query itself so it isn't executed. Even if address contained '); drop table Users;-- it wouldn't be executed.
Another option is to use a microORM like Dapper. Dapper uses reflection to map parameter names and data properties to create and execute parameterized queries:
var insertStmt="INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress) " +
"VALUES (#name,#email,#address)";
connection.Execute(insertStmt, new { name=someName,email=someEmail, address=someAddress});
As the project's page shows, you can execute the same query multiple times if you pass an array of parameters :
var myItems=new[]
{
new {name=someName,email=someEmail, address=someAddress}
};
connection.Execute(insertStmt, myItems);
You should use parameterized queries, for example if you are using ADO.NET, use this:
. . .
using(SqlConnection connection = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = #"INSERT INTO [CustomerInfo] (CustomerName, CustomerEmail, CustomerAddress)
VALUES (#Name, #Email, #Address)";
cmd.Parameters.AddRange(new SqlParameter[]
{
new SqlParameter("#Name", name),
new SqlParameter("#Email", email),
new SqlParameter("#Address", address)
});
connection.Open();
cmd.ExecuteNonQuery();
}
. . .
other sql provider type examples you can find here.
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?
string sql = "insert into tblmain values('" + txtName.Text + "','" + txtPost.Text + "','" + DropDownList1.SelectedItem + "')";
If the user inserts My name's first later is D ! in txtPost, then it gives error that 's are not allowed.
Can you please send me the code to accept this type of character from textbox in .net (C#).
You sample is the book example of SQL injection in most pure form. ' closes the previous quote and the rest of SQL command is interpreted differently from what you expect.
There is no excuses to not using parametrized queries when dealing with non-hardcoded values and SqlConnection directly.
Also check these articles for mre details. Approximate sample (need more fields and not showing exception handling):
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("insert into tblmain values(#name")", connection);
command.Parameters.Add("#name", SqlDbType.String);
command.Parameters["#name"].Value = customerID;
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
The second problem you may hit is if you pick wrong field type for the text - to be able to store characters you want you need Unicode string. Check out C#: DbType.String versus DbType.AnsiString post for details.