ExecuteNonQuery() returns -1 - c#

For some reason result is always -1 and nothing get added to the database. I executed the query in SQL Server and it runs fine. I don't get any exception whatsoever and I don't use any stored procedure.
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=RAINBOW;Integrated Security=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)", con);
cmd.Parameters.AddWithValue("#item_desc", txtitemdesc.Text);
cmd.Parameters.AddWithValue("#cat_id", GetCategoryID());
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
Edit
int GetCategoryID()
{
int cat_id = 0;
cmd = new SqlCommand("SELECT category_id FROM ItemDetails.category WHERE category_desc=#cat_desc", con);
con.Open();
cmd.Parameters.AddWithValue("#cat_desc", cboCategory.Text);
reader = cmd.ExecuteReader();
while (reader.Read())
{
cat_id = int.Parse(reader["category_id"].ToString());
}
reader.Close();
con.Close();
return cat_id;
}

If possible then don't use AddWithValue(). Actually when you are not providing type explicitly, it will try to convert implicitly and sometimes the implicit conversion may not be the most optimal of conversions. You can find some more discussion in this link.
And most important thing is don't forget to clear parameters before assign, by using this line.
cmd.Parameters.Clears();
Check below code.
string sqlQuery = "INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)";
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clears(); // Add this same line in your getcategory function.
cmd.Parameters.Add("#item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text;
cmd.Parameters.Add("#cat_id", SqlDbType.Int).Value = GetCategoryID();
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
}

Related

Get Value of specific Column while Login (C# Mysql)

I am trying to make a login at the moment. I watched some videos and found a good way. Every user has an id, Username and Password. I want to get the id of the user who has just been logged in and save it in an Integer. I also tried it with an ExecuteReader but I get an Exception(MySql.Data.MySqlClient.MySqlException).
My current Code is:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT COUNT(1) FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
//Login correct
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
The try with the ExecuteReader:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT id,Username,Password FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
MessageBox.Show("Test: " + datareader.GetString("id"));
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
I hope somebody can help me. Thank you in advance.
Try and use the Read method:
if(datareader.Read()){
MessageBox.Show("Test: "+datareader.GetString(0));
}
EDIT:
To make good use and disposal of resources I recommend using the MySqlDataReader inside a using block, e.j.
using(MySqlDataReader reader = new sqlCmd.ExecuteReader()){
if(reader.Read()){
MessageBox.Show("Test: "+reader.GetString(0));
}
}
I found a solution to my Question by myself. I forgot the while(datareader.Read()) in the ìf(datareader.HasRows) query. Here is my working Code:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT * FROM Users_Table WHERE username=#Username AND password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
while (datareader.Read())
{
UserID = datareader.GetInt32("id");
}
}
else
{
//Incorrect Password
}
}
catch
{
//Error
}
finally
{
sqlCon.Close();
}

double data inserted in sql c#

This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
Sample image of the double entry in the database.
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (#name,#pos,#username,#password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pos", textBox4.Text);
cmd.Parameters.AddWithValue("#username", textBox2.Text);
cmd.Parameters.AddWithValue("#password", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You're calling ExecuteNonQuery() twice.
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
you excecute the query twice.
change:
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
to
con.Open();
int result = cmd.ExecuteNonQuery();

Insert in c# using npgsql

When I'm trying to execute an insert query with npgsqlcommand to postgres in c#, the execution of the program is suspend to cmd.ExecuteNonQuery();
Here's my code
public void Insert(Mouvement mvt)
{
NpgsqlConnection conn = null;
NpgsqlCommand cmd = null;
try
{
conn = UtilDB.GetConnection();
String sql = "INSERT INTO MOUVEMENT(ID_AERONEF,ID_PF,ID_ESCALE,DATE,SENS,NVOL,PISTE,BLOC,PAXC,PAXY,PAXBB,PAXEXO," +
"TRANSITDIRECT,TRANSITRI,TRANSITRRLC,CONTINU,PN,FRETPAYANT,FRETGRATUIT,BAGAGE,POSTE,MODE,BALISAGE,OBSERVATION) "+
"VALUES (:id_aeronef,:id_pf,:id_escale,:date,:sens,:nvol,:piste,:bloc,:paxc,:paxy,:paxbb,:paxexo," +
":transitdirect,:transitri,:transitrrlc,:continu,:pn,:fretpayant,:fretgratuit,:bagage,:poste,:mode,:balisage,:observation)";
conn.Open();
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.Add("id_aeronef", mvt.Aeronef.Id);
cmd.Parameters.Add("id_pf", mvt.Plateforme.Id);
cmd.Parameters.Add("id_escale", mvt.Escale.Id);
cmd.Parameters.Add("date", mvt.Date);
cmd.Parameters.Add("sens", mvt.Sens);
cmd.Parameters.Add("nvol", mvt.Nvol);
cmd.Parameters.Add("piste", mvt.Piste);
cmd.Parameters.Add("bloc", mvt.Bloc);
cmd.Parameters.Add("paxc", mvt.PaxC);
cmd.Parameters.Add("paxy", mvt.PaxY);
cmd.Parameters.Add("paxbb", mvt.PaxBB);
cmd.Parameters.Add("paxexo", mvt.PaxExo);
cmd.Parameters.Add("transitdirect", mvt.TransitDirect);
cmd.Parameters.Add("transitri", mvt.TransitRI);
cmd.Parameters.Add("transitrrlc", mvt.TransitRRLC);
cmd.Parameters.Add("continu", mvt.Continu);
cmd.Parameters.Add("pn", mvt.Pn);
cmd.Parameters.Add("fretpayant", mvt.FretPayant);
cmd.Parameters.Add("fretgratuit", mvt.FretGratuit);
cmd.Parameters.Add("bagage", mvt.Bagage);
cmd.Parameters.Add("poste", mvt.Poste);
cmd.Parameters.Add("mode", mvt.Mode);
cmd.Parameters.Add("balisage", mvt.Balisage);
cmd.Parameters.Add("observation", mvt.Observation);
cmd.Prepare();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(cmd!=null) cmd.Dispose();
if(conn!=null) conn.Close();
}
}
Finally, it was a problem of type: I have character(1) in database but String(10) in C#

Attempt to insert a row in database table fails

I'm trying to put anything into my DB. Message Box is showing that I did put 1 row to DB, but when I check it - nothing happened.
Anybody know the cure?
SqlCeConnection cn = new SqlCeConnection(#"Data Source = Database1.sdf");
try
{
cn.Open();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
SqlCeCommand cm = new SqlCeCommand("INSERT INTO Sentences (Sentence) VALUES ('Sentence')", cn);
//cm.Parameters.AddWithValue("#Sentence", "Any sentence");
try
{
int rowsAffected = cm.ExecuteNonQuery();
MessageBox.Show((rowsAffected.ToString()));
}
catch (Exception)
{
MessageBox.Show("Insertion Failed");
}
cn.Close();
Try some nice and easy code.
using (SqlCeConnection con = new SqlCeConnection(strConn))
{
try
{
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("insert into Table (column1,Column2) values (#Val1, #val2)", con))
{
cmd.Parameters.AddWithValue("#Val1", value1);
cmd.Parameters.AddWithValue("#Val2", value2);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
con.Close();
} catch (Exception ex){
//handle any exception here
}
}
suggest you to use a full path to your database file in your connection string.
complete example like =
#"Data Source=C:\Users\MYPC\Documents\Visual Studio
2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist
Security Info=False;"
Well explained here !!

winforms C# using sql server 2008

private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code, but there is a problem if there is no data in my table it will not accept.
So I want to use if no data is present it should take CustomerId as 1
It will be NULL of there are no rows so you can:
"select isnull(max(CustomerId), 1) as Id from CustomerDetails"
You should also look at ExecuteScalar which is designed for a singe result.
Try like this
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
}
else
{
sid.Text = "1"
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources