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();
Related
I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.
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();
}
}
con.Open();
cmd = new OleDbCommand("insert into login (user, password) values ('" +textBox1 .Text + "','" + textBox2 .Text + "');",con);
cmd.CommandType = CommandType.Text;
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
con.Close();
when i try to insert some of error appear ( syntax error in INSERT STATEMENT )
i'm try different method to values like Parameters or direct
plz !
Escape reserved keyword user
use parameterized query
avoid sql injection
Make use of disposable objects
Try this approach:
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(
"insert into login ([user], [password]) values (#user, #pass);",
con))
{
cmd.Parameters.Add(new OleDbParameter("#user", textBox1.Text ));
cmd.Parameters.Add(new OleDbParameter("#pass", textBox1.Text ));
if (temp > 0)
{
textBox1.Text = String.Empty;
textBox2.Text = String.Empty;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
}
}
I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).
Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.
My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}
I am trying to code a register application form. In the code below I want to check if the username exists before i save the data in Database.
The problem here that the code doesn't go to the "else" statement.
Do I miss something? Kindly help
public void UserNameCheck()
{
string connetionString = null;
SqlConnection con;
connetionString = "Data Source=MCOEELIMENEM\\sqlexpress;Initial Catalog=Database;Integrated Security=True";
con = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand("Select * from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Username = " + dr[1].ToString() + " Already exist");
break;
}
else
{
cmd.CommandText = "insert into Register(Username,Password,Fullname,MobileNO,EmailID) values( #Username, #Password, #Fullname, #MobileNO, #EmailID)";
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Fullname", textBox3.Text);
cmd.Parameters.AddWithValue("#MobileNO", textBox4.Text);
cmd.Parameters.AddWithValue("#EmailID", textBox5.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Succesfully");
con.Close();
this.Hide();
Login lg = new Login();
lg.Show();
}
}
}
The query will not return any rows (therefore the Read() statement will fail) where the user exists.
Try this (untested):
SqlCommand cmd = new SqlCommand("Select count(*) from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var result = cmd.ExecuteScalar();
if (result != null)
{
MessageBox.Show(string.format("Username {0} already exist", this.textBox1.Text));
}
else
{
...
If dr.Read() returns true, then your reader always has rows.
EDIT:
As long, as you do not getting any values from DB, you can remove while(dr.Read()) statement, and your code will work as you need
I recommand you to not select all columns, instead just select id and check with ExecuteScalar method of SqlCommand, that would be optimum solution.
SqlCommand cmd = new SqlCommand("Select id from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var nId = cmd.ExecuteScalar();
if(nId != null)
{
// Prompt user is already exists
}
else
{
// Insert record
}
You must check with the number of rows returned by the query.