How can I fix this ? I try to stop duplication in my attendance but I can't solve this. I try to cast from date.
if(label1.Text != "" && label2.Text != "" && label3.Text != "")
{
try
{
string c = #"(select count(*)from Attendance where Date='"+label1.Text+"')";
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
con.Open();
MySqlCommand cmdc = new MySqlCommand(c,con);
int count = (int)cmdc.ExecuteScalar();
if(count > 0)
{
MessageBox.Show("This data is already IN");
}
else
{
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.VarChar).Value = label1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label2.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Attendance Inserted");
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
It seems that you are looking for insert ignore MySql syntax. Be careful with sql parameters: if query wants DateTime (#Date parameter), provide DateTime (DateTime.ParseExact and alike):
string sql =
#"insert ignore Attendance(
Name,
Date,
empIn)
values(
#Name,
#Date,
#empIn)";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql, con)) {
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
// If Date is DateTime, provide DateTime, not string
//TODO: provide the right date time format here
cmd.Parameters.Add("#Date", MySqlDbType.DateTime).Value =
DateTime.ParseExact(label1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label2.Text;
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Attendance Inserted");
else
MessageBox.Show("This data is already IN");
}
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.
Hello everyone goodevening, i have a question.. how can i prevent duplicate insert data to my database. my logic is when he IN in morning and the date is march 7 2019
he insert and when he attempt to IN again in march 7 2019 the message box will show that ("He Already In") and when he In March 8 2019, he can In again in short if he IN now he can be In on another day again how can i fix this i have some codes here
MySqlDataReader dr;
if (con != null && con.State == ConnectionState.Closed)
{
con.Open();
}
MySqlCommand cmd = new MySqlCommand("Select * from attendance1 where empID=#empID AND Name=#Name AND Date=#Date", con);
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = empID.ToString();
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label6.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label4.Text);
dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("You are already In");
}
else
{
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO attendance1(empID,Name,Date,MorningIn)values(#empID,#Name,#Date,#MorningIn)", con);
cmd1.Parameters.Add("#empID", MySqlDbType.VarChar).Value = empID.ToString();
cmd1.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label6.Text;
cmd1.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label4.Text);
cmd1.Parameters.Add("#MorningIn", MySqlDbType.VarChar).Value = label2.Text;
cmd1.ExecuteNonQuery();
MessageBox.Show("OK");
}
if (con != null && con.State == ConnectionState.Open)
{
con.Close();
}
he error because the connection is open... what strategy can i do ?
you are opening the connection twice here,
1) Remove all con.Open(); and con.Close()
2) Add after MySqlDataReader dr;
if (con != null && con.State == ConnectionState.Closed)
{
con.open();
}
3) In the end in the last command line write
if (con != null && con.State == ConnectionState.Open)
{
con.close();
}
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();
I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.
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");
}
}
}