Syntax error in UPDATE clause - c#

I am trying to update a value in an MS-Access database.
The query works fine when entered directly into Access, but when I try to update it within C#, I get a "Syntax Error in the UPDATE clause" exception.
conMngr.ConnectionStr = ConfigurationManager.ConnectionStrings[_connectionStr].ConnectionString;
conMngr.OpenConnection();
try {
string query = "select Id, counter from tabAppCounter where userId=" + _userId.ToString() + " and appPath = '" + path + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conMngr.DbCon);
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
if (ds.Tables[0].Rows.Count != 0) {
int count = int.Parse(ds.Tables[0].Rows[0].ItemArray[1].ToString())+ 1;
string query2 = "UPDATE tabAppCounter set counter=#count where Id=#Id";
conMngr.OleDbcmd = new OleDbCommand(query2, conMngr.DbCon);
conMngr.OleDbcmd.Parameters.AddWithValue("#Id", ds.Tables[0].Rows[0].ItemArray[0].ToString());
conMngr.OleDbcmd.Parameters.AddWithValue("#count", count.ToString());
conMngr.OleDbcmd.ExecuteNonQuery();
}
} catch (Exception e) {
MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
}
conMngr.CloseConnection();
This code fails after the ExecuteNonQuery with a Syntax error in UPDATE clause exception.
I have tried using a prebuilt query string, but that does not work either.

The access driver (and Ole) do not use named parameters, they are positional based. The order you pass your parameters AND the parameters in your update statement do not match and this will give you an error.
You really should be using ? for the placeholder in the update string.
string query2 = "UPDATE tabAppCounter set counter=? where Id=?";
conMngr.OleDbcmd = new OleDbCommand(query2, conMngr.DbCon);
conMngr.OleDbcmd.Parameters.AddWithValue("#count", count.ToString());
conMngr.OleDbcmd.Parameters.AddWithValue("#Id", ds.Tables[0].Rows[0].ItemArray[0].ToString());
conMngr.OleDbcmd.ExecuteNonQuery();
Finally make sure the types are correct, the passed in type must match the type in the database. So if count is an int in both places then pass count and not count.ToString()

In hopes this is going to be helpful to others: This is what worked for me.
Instead of
string query2 = "UPDATE tabAppCounter set counter=#count where Id=#Id";
I used
string query2 = "UPDATE [tabAppCounter] set [counter]=#count where [Id]=#Id";
and magically, everything started to work correctly.

Related

Show data in Textboxes from database in C#

Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error

+1 to data column using SQL Server Compact 4.0

I am trying to create a simple button, that when clicked, adds 1 to the related column. I use a dropdown box to select the ID, then add 1 to the value. However, I am presented with the error:
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll
and it highlights cm.ExecuteNonQuery();
I have gone through several attempts at this but it's getting me a little confused as to why I can't simply run the SQL statement.
Here is the code
private void button2_Click(object sender, EventArgs e) {
try {
SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text, mySqlConnection);
cm.ExecuteNonQuery();
} catch (SqlCeException) {
MessageBox.Show("Error");
}
}
"UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text + "'"
Need to close the string parameter with ' in query?
Your command has a opening apostrophe which is not being closed. This should fix it.
SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text + "'", mySqlConnection);
But that's a security issue since the user can manage to add extra commands to your query, which could ruin your entire database.
This is a better solution since using parameters is more safe.
SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = #fixedid;", mySqlConnection);
cm.Parameters.AddWithValue("#fixedid", comboBox1.Text);
This will prevent future headaches.
This question has better detailed answers that may help enlighten your mind...
You need to think about below things;
User must select a value.
Security
Dispose the command after using it.
string selectedValue = comboBox1.Text;
if (string.IsNullOrEmpty(selectedValue))
{
MessageBox.Show("Please select something");
return;
}
string sql = "UPDATE fixedBugs SET Success = ISNULL(Success,0) + 1 WHERE Fixed_ID = #selectedValue";
try
{
using (SqlCeCommand cm = new SqlCeCommand(sql, mySqlConnection))
{
SqlCeParameter param = new SqlCeParameter("#selectedvalue", SqlDbType.NText);
cm.Parameters.Add(param);
cm.Parameters["#selectedvalue"].Size = 50;
cm.Parameters["#selectedvalue"].Value = selectedValue.Trim();
cm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
PS: Code is not tested.

C# and SQLCE Database Not Updating

Ok, I have been having a problem the last few days with my database not updating. I can read the data fine and I'm not getting any exceptions either. I'm trying to update the database then I try to read values again after the update (during same run), and they still hold the original values, so it doesn't seem to be an issue with the database being copied to another folder (I'm using Copy if newer yet neither database is being updated).
Here is the code I'm using. As you can see I tried a few different approaches, none of which worked yet.
public void UpdateDatabaseInStock(string itemName, string tableName)
{
DataSet data = new DataSet("Items");
int val;
//get the file path to the database as a string
string dbfile =
new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName +
"\\Database\\GameData.sdf";
//connect to the database
using (SqlCeConnection cntn = new SqlCeConnection("datasource=" + dbfile))
{
//create an adapter to pull all data from the table
using (SqlCeDataAdapter adpt = new SqlCeDataAdapter
("SELECT * FROM " + tableName + " WHERE Name LIKE '%" + itemName + "%'", cntn))
{
//put the data into a DataSet
adpt.Fill(data);
cntn.Close();
}
//fill the data from the Items table into a DataTable to return.
DataTable itemTable = data.Tables[0];
DataRow a = itemTable.Rows[0];
val = (short)a.ItemArray[3] - 1;
dbfile = "";
data.Dispose();
itemTable.Dispose();
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = cntn;
cntn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE " + tableName + " SET [In Stock] = #Value WHERE [Name] = '#ItemName'";
//cmd.Parameters.Add("#Value", SqlDbType.SmallInt);
//cmd.Parameters["#Value"].Value = val;
//cmd.Parameters.Add("#ItemName", SqlDbType.NChar, 75);
//cmd.Parameters["#ItemName"].Value = itemName;
cmd.Parameters.AddWithValue("#Value", val);
cmd.Parameters.AddWithValue("#ItemName", itemName);
cmd.ExecuteNonQuery();
//close the conenction
cntn.Close();
cmd.Dispose();
}
}
Any ideas to get it to actually update?
Just a hunch (can't corroborate this on msdn): could it be that using nchar(75) adds spaces to the parameter, thereby causing the WHERE clause to fail?

C# reading int from mysql

Having problem reading a value from my table in mysql, is the index value i cant read the value back no matter what. all i get is the initialized value of 0 i dont get any error because it return 0, if i run the query in the database it get the correct value. i tried to use executeScalar() but with the same result .
MySqlConnection conn = new MySqlConnection(MyConString);
ulong ukey=0;
try
{
string sql_users2 = "SELECT `key` FROM `permuser` WHERE `user` = '" + myuser + "' AND `code` = '" + mycode + "'";
MySqlCommand cmdSel2 = new MySqlCommand(sql_users2, conn);
conn.Open();
MySqlDataReader dr2 = cmdSel2.ExecuteReader();
dr2.Read();
ukey = dr2.GetUInt64(dr2.GetOrdinal("key"));
// MessageBox.Show("Sorry " + myuser + " already have access to " + mycode + ",\nIf this is an extension, search for the user which key is " + ukey + " and edit the end date.", "Duplicate User Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
dr2.Close();
dr2.Dispose();
}
catch (MySqlException ex) //catch 2
{
MessageBox.Show("catch ukey\nCan't connect to database\n" + ex.ToString());
}
conn.Close();
conn.Dispose();
You are returning a single value from your query, so you could use directly ExecuteScalar instead of ExecuteReader. (the link point to the description for SqlServer, but it is the same for MySql)
An important question to never forget is the usage of parameters instead of string concatenation.
What happen if your myuser or mycode variables contain a single quote? You get wrong results or syntax errors.
Of course, the main problem is the Sql Injection attack to never understimate.
using(MySqlConnection conn = new MySqlConnection(MyConString))
{
ulong ukey=0;
try
{
string sql_users2 = "SELECT `key` FROM `permuser` WHERE `user` = #usr AND `code` = #code";
MySqlCommand cmdSel2 = new MySqlCommand(sql_users2, conn);
conn.Open();
cmdSel2.Parameters.AddWithValue("#usr", myuser);
cmdSel2.Parameters.AddWithValue("#code", mycode);
object result = cmdSel2.ExecuteScalar();
if(result != null)
ukey = Convert.ToUInt64(result);
}
catch (MySqlException ex) //catch 2
{
MessageBox.Show("catch ukey\nCan't connect to database\n" + ex.ToString());
}
}
also I am a bit perplexed about your usage of UInt64. What kind of datatype is stored in the key column?
way is many simply:
ukey = (uint)dr2[0];

Problem with WHERE columnName = Data in MySQL query in C#

I have a C# webservice on a Windows Server that I am interfacing with on a linux server with PHP. The PHP grabs information from the database and then the page offers a "more information" button which then calls the webservice and passes in the name field of the record as a parameter. So i am using a WHERE statement in my query so I only pull the extra fields for that record. I am getting the error:
System.Data.SqlClient.SqlException:Invalid column name '42'
Where 42 is the value from the name field from the database.
my query is
string selectStr = "SELECT name, castNotes, triviaNotes FROM tableName WHERE name =\"" + show + "\"";
I do not know if it is a problem with my query or something is wrong with the database, but here is the rest of my code for reference.
NOTE: this all works perfectly when I grab all of the records, but I only want to grab the record that I ask my webservice for.
public class ktvService : System.Web.Services.WebService {
[WebMethod]
public string moreInfo(string show) {
string connectionStr = "MyConnectionString";
string selectStr = "SELECT name, castNotes, triviaNotes FROM tableName WHERE name =\"" + show + "\"";
SqlConnection conn = new SqlConnection(connectionStr);
SqlDataAdapter da = new SqlDataAdapter(selectStr, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
DataTable dt = ds.Tables["tableName"];
DataRow theShow = dt.Rows[0];
string response = "Name: " + theShow["name"].ToString() + "Cast: " + theShow["castNotes"].ToString() + " Trivia: " + theShow["triviaNotes"].ToString();
return response;
}
}
Quick solution:
I believe you need single quotes in your selectStr:
string selectStr =
"SELECT name, castNotes, triviaNotes FROM tableName WHERE name = '" + show + "'";
More information:
In .NET, you'll want to be sure you close out any connections explicitly when you no longer need them. The easiest way to do this is to wrap using statements around any types that implement IDisposable, such as SqlConnection in this case:
using(SqlConnection conn = new SqlConnection(connectionStr))
{
SqlDataAdapter da = new SqlDataAdapter(selectStr, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
DataTable dt = ds.Tables["tableName"];
DataRow theShow = dt.Rows[0];
string response = "Name: " + theShow["name"].ToString() + "Cast: " + theShow["castNotes"].ToString() + " Trivia: " + theShow["triviaNotes"].ToString();
return response;
}
Additionally, it looks like your code could be easily subject to SQL injection. What if someone submits a form with the value: fake name' OR 1=1;DROP DATABASE someDbName;--?
You'll want to take advantage of SQL parameters, something like:
SqlCommand cmd = new SqlCommand(
"SELECT name, castNotes, triviaNotes FROM tableName WHERE name = #show", conn);
cmd.Parameters.AddWithValue("#show", show);
Shouldn't the WHERE clause be WHERE name = '" + show + "'"; Strings should be enclosed in single quotes and not double quotes for SQL statements.
Also the System.Data.SqlClient namespace is for SQL Server and not MySQL. See MySQL official docs for connecting to MySQL via C#.

Categories

Resources