No Messagebox showing - c#

I have a script that connects itself with a mysql server and makes an sql query if I press a button.
My code:
try
{
MySqlConnection c = new MySqlConnection("Server=****;Database=*****;Uid=****;Pwd=y u no want to know ma pw;");
MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = '" + textBox1.Text + "'", c);
MySqlDataReader myReader;
c.Open();
myReader = cmd.ExecuteReader();
int cnt = 0;
while(myReader.Read())
{
cnt = cnt + 1;
}
if (cnt == 1)
{
MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
}
}
catch(Exception ex)
{
MessageBox.Show("Benutzer konnte nicht entfernt werden.\n\n" + ex.ToString());
}
Why isn't the message box showing?

You need to use the ExecuteNonQuery() method of your MySqlCommand object, which will return the row(s) affected - which i suspect you are looking for. A DELETE statement will not return a resultset, only the records affected.
using(MySqlConnection c = new MySqlConnection("Server=**;Database=***;Uid=**;Pwd=**;"))
{
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = #name"))
{
var userParam = new MySqlParameter();
userParam.Name = "#name";
userParam.Value = textbox1.Text;
cmd.Parameters.Add(userParam);
c.Open();
var recordsAffected = cmd.ExecuteNonQuery();
c.Close();
if (recordsAffected == 1)
{
MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
}
}
}

Related

i get the error MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}

How to open next form base on select query base on flag

I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want

SQL statement to retrieve all data or transactions from database of a particular Id and plot same on a graph in asp.net

Below is the description.
**Table**
Pid memberId name date taxAmount
1 04 Sam 1/1/16 £10
2 07 John 1/4/16 £12
3 04 Sam 2/5/16 £17
4 06 Paul 3/5/16 £10
5 04 Sam 5/6/16 £10
Say I want to retrieve Sam's or any other persons' transactions from the database in Asp.net. Please what is the sql statement?
Sorry guys,please below is my complete code. I tried it but it didn't work.I would be glad is someone can help.
{
OleDbConnection conn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString);
try
{
conn.Open();
string checkuser = "select count(*) from RegisteredMember where firstName='" + txtFirstName.Text + "'";
OleDbCommand cmd = new OleDbCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkUserIDQuery = "select memberID from RegisteredMember where firstName='" + txtFirstName.Text + "'";
OleDbCommand IDcmd = new OleDbCommand(checkUserIDQuery, conn);
string memberID = IDcmd.ExecuteScalar().ToString();
if (memberID == txtUserID.Text)
{
Session["New"] = txtUserID.Text;
OleDbCommand Plotcmd = new OleDbCommand();
cmd.Connection = conn;
string query = "select * from payment where memberID= "+ txtMemberID.Text + "'";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Chart1.Series["Tax History"].Points.AddXY(reader["date"].ToString(), reader["taxAmount"].ToString());
}
}
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Shamila Stuff\campus\semester 2\comp 1551-Application and Web Developement\asp\fwp\fwp\FwpDatabase.accdb"; // put your path
myConnection = new OleDbConnection(connString);
string query = "select * from payment where memberID= '"+ txtMemberID.Text + "'";
if (myConnection == null)
myConnection = GetConnection();
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Write(ex);
}
finally
{
myConnection.Close();
}
try
{
myConnection.Open();
OleDbDataReader reader = myCommand.ExecuteReader();
if (reader.HasRows == true)
{
reader.Read();
string myQuery1 = Chart1.Series["Tax History"].Points.AddXY(reader["date"].ToString(), reader["taxAmount"].ToString());
myCommand = new OleDbCommand(myQuery1, myConnection);
myCommand.ExecuteNonQuery();
reply = true;
}
else
{
reply = false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
myConnection.Close();
}
Put your connections string for the database in the mentioned place.

Display mySql table in a label in C#

I'm trying to implement an application combine with mysql database. I want to show table1 like in a terminal view instead of displaying it in a datagrid view. I'm using the code below to connect and display from MySql Database:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
label1.Text = myReader[0].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
This code only execute the last value of the table. but, I want to display whole table plus I want it to show in a label. So that I can style it like a terminal view.
Any help on this would be great.
Thanks in Advanced!
I think MySqlDataReader.FieldCount Property will be useful.
Try this code:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
if(label1.Text.Length > 0)
label1.Text += Environment.NewLine;
for(int i=0; i<myReader.FieldCount; i++)
label1.Text += myReader[i].ToString() + " ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
NOTE: It is recommeded to use using statement for mysqlconnection, mysqldatareader and mysqlcommand.
UPDATE (using StringBuilder as recommended by jmcilhinney):
// Method used to retrieve data from DB
string GetFormattedText()
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection myConn = new MySqlConnection(myConnection))
{
myConn.Open();
using (MySqlCommand command = myConn.CreateCommand())
{
command.CommandText = "Select * FROM database_name.table1";
using (MySqlDataReader myReader = command.ExecuteReader())
{
try
{
StringBuilder sb = new StringBuilder();
while (myReader.Read())
{
if (sb.Length > 0)
sb.Append(Environment.NewLine);
for (int i = 0; i < myReader.FieldCount; i++)
sb.AppendFormat("{0} ", myReader[i]);
}
return sb.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
return string.Empty;
}
Usage:
label1.Text = GetFormattedText();

C# SQL Server CE - Update won't work

I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.

Categories

Resources