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.
Related
I'm trying to get if a value already exists in my database for a registration and I've searched everywhere for an answer but I get this error:
" You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near...at line 1".
I don't know what I'm doing wrong...
void Start()
{
linhaConn = "Server=localhost;" +
"Database=jogo;" +
"User ID=root;" +
"Password=;" +
"Pooling=false;" +
"CharSet=utf8";
ConnDatabase(linhaConn);
}
void ConnDatabase(string lConn)
{
conn = new MySqlConnection(lConn);
conn.Open();
print("Conectado");
}
public void InserirDB()
{
ConnDatabase(linhaConn);
txtUser = InpUserCriar.text;
txtEmail = InpEmail.text;
command = new MySqlCommand("select * from jogador where ([email] = '" + txtEmail + "')", conn);
int UserExist = (int)command.ExecuteScalar();
if (UserExist > 0)
{
print("already exists");
}
else
{
print("doesnt exists");
}
conn.Close();
EDIT
I did it! Here is the code:
ConnDatabase(linhaConn);
txtUser = InpUserCriar.text;
txtEmail = InpEmail.text;
string countDataEmail;
command = new MySqlCommand("select count(*) from jogador where email= '" + txtEmail+ "' ;", conn);
countDataEmail = command.ExecuteScalar().ToString();
if (countDataEmail == "0")
{
print("it doesnt exist");
}
else
{
print("email already exists");
}
If you just want to check if they query returns ant row you can use UserExist.HasRows
I just wanted to mention SQL Injection! Whenever dealing with User Input make sure they can't harm or retrieve something from your database. See the example which uses a prepared statement to avoid that.
besides that, are you sure it should be
... where ([email] = some#email.address)
instead of (how I know SQL queries)
... where email = some#email.adddres;
So together it would probably be something like
command = new MySqlCommand("select * from jogador where email = #email;", conn);
command.Parameters.AddWithValue("#email", txtEmail);
commandPrepare();
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
In my winforms application i want to update database values using form. i managed to create every other part get to work other than this.when i tried to update my database it giving me some strange sql error. i have not idea what's wrong with my code
it shows me error like this
you have an error in your sql syntax check the manual that corresponds to your mysql server version
and this is the code that i used to update the database.can someone please check this code for me
private void button1_Click(object sender, EventArgs e)
{
string constring = string.Format("datasource='{0}';username=***************;port=3306;password=**********;Connect Timeout=20000;Command Timeout=28800", serverip.Text);
string Query = "update wartif.userdata set (citrixpass= '" + this.citrix_pass_box.Text + " ', idmpass = '" + this.IDM_pass_box.Text + "' , mortracpass = '" + this.mortrac_pass_box.Text + "' , detpass = '" + this.DET_pass_box.Text + "' where username = '" + this.Pwloggeninaslable.Text + "' ;";
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(Query, conwaqDatabase);
MySqlDataReader myreader;
try
{
conwaqDatabase.Open();
myreader = cmdwaqDatabase.ExecuteReader();
while (myreader.Read()) { }
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You open a parenthesis before the SET clause (not needed) but you forget to close it at the end
However, let me show you how you should write this code to avoid sql injection and parsing problems
string constring = .....;
string Query = #"update wartif.userdata set citrixpass=#ctx, idmpass = #idm,
mortracpass = #mtc, detpass = #det where username = #usr;";
using(MySqlConnection conwaqDatabase = new MySqlConnection(constring))
using(MySqlCommand cmdwaqDatabase = new MySqlCommand(Query, conwaqDatabase))
{
try
{
conwaqDatabase.Open();
cmdwaqDatabase.Parameters.AddWithValue("#ctx", this.citrix_pass_box.Text);
cmdwaqDatabase.Parameters.AddWithValue("#idm", this.IDM_pass_box.Text);
cmdwaqDatabase.Parameters.AddWithValue("#mtc", this.mortrac_pass_box.Text);
cmdwaqDatabase.Parameters.AddWithValue("#det", this.DET_pass_box.Text);
cmdwaqDatabase.Parameters.AddWithValue("#usr", this.Pwloggeninaslable.Text);
int rowsUpdated = cmdwaqDatabase.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In this way you don't need to worry about malicious user that tries to break your code with an Sql Injection attack, your query string is more readable and you don't need to worry about passing strings that contains single quote or correctly formatting dates and decimals
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];
I have two DataGridView controls.
For the second one, I just copy-pasted the code from the first and changed where the difference was. But I get an error at the second when I want to view the result of my SQL code.
Translated in English the error show something like that there was no value given to at least one required parameter.
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";
try
{
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT zivila.naziv,(obroki_save.skupaj_kalorij/zivila.kalorij)*100 as Kolicina_v_gramih "
+ "FROM (users LEFT JOIN obroki_save ON obroki_save.ID_uporabnika=users.ID) "
+ "LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila"
+ "WHERE users.ID= " + a.ToString();
loadDataGrid(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
public void loadDataGrid(string sqlQueryString)
{
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.ReadOnly = true;
dataGridView1.Columns[0].Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";
try
{
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT skupaj_kalorij "
+ "FROM obroki_save "
+ "WHERE users.ID= " + a.ToString();
loadDataGrid2(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
public void loadDataGrid2(string sqlQueryString)
{
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView2.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView2.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView2.DataSource = data;
dataGridView2.AllowUserToAddRows = false;
dataGridView2.ReadOnly = true;
dataGridView2.Columns[0].Visible = true;
}
You'd be far better off reading and doing this tutorial:
http://msdn.microsoft.com/en-us/library/ms171884(v=VS.80).aspx
It will probably take about 20 minutes to complete
And then (as needed) the rest of them (google for Data Walkthroughs)
They will teach you how to do your data access properly and, after becoming familiar with the advanced tools in Visual Studio for connecting to databases, you'll be able to generate an app that will show database contents in a grid, and save them back to the db, faster than it took you to even write your post here..
The code will be high performance, more secure and easier to write than what you have here - the code you have here is low quality, prone to SQL injection attacks, not modular or arranged in a way that is suited to the language youre using and takes a long time to write; all in, it has no good points at all (please don't be offended)
I thoroughly recommend scrapping the entire thing and starting again, doing things in the way advocated by Microsoft's tutorial. It might seem like the wrong thing to do after you've poured so many hours into this broken, bad way of doing things, but trust me.. You'll be glad you did; 20 minutes investment now will save you thousands of hours of coding in the future
One final point, if your database data doesnt seem to be saving changes when you do things the way the tutorial tells you to, click on the database in Solution Explorer and change "Copy to Output Directory" to "Copy if Newer" - c# is updating your database but youre either looking in the wrong DB to check whether it worked, or Visual Studio is replacing your edited database with a new one every time you start your app
I think the problem is in private void button2_Click() with
a.ToString();
What's a?
Try putting quotes around a.Tostring():
string queryString = "SELECT zivila.naziv,(obroki_save.skupaj_kalorij/zivila.kalorij)*100 as Kolicina_v_gramih "
+ "FROM (users LEFT JOIN obroki_save ON obroki_save.ID_uporabnika=users.ID)"
+ " LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila "
+ " WHERE users.ID= '" + a.ToString() + "'";
or use string.format():
string queryString = string.format("SELECT zivila.naziv,(obroki_save.skupaj_kalorij/zivila.kalorij)*100 as Kolicina_v_gramih "
+ "FROM (users LEFT JOIN obroki_save ON obroki_save.ID_uporabnika=users.ID)"
+ " LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila "
+ " WHERE users.ID= '{0}'", a);