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();
}
Related
I'm trying to create simple log in page with visual studio win form. I have got username and password as textbox controls.
here is the event which should check if there is such kind of user in database:
if (con.State != ConnectionState.Open)
{
con.Open();
}
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "select staff_username, staff_password from staff_accounts";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if (username.Text == dr["staff_username"].ToString() && pass.Text == dr["staff_password"].ToString())
{
admin.ShowDialog();
}
else
{
label1.Text = "Error";
}
}
}
dr.HasRows returns false, so it means that cmd.CommandText = "select staff_username, staff_password from staff_accounts"; returns no rows, but in my database the same query works fine.
any kind of help will be appreciated.
You should check HasRows property before calling reader Read() method. Try:
if (dr.HasRows)
{
while (dr.Read())
{
....
This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 3 years ago.
private void btnadd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = INFINITY; Initial Catalog = Stock; Integrated Security = True"); // making connection
SqlCommand cmd;
int ud = 0;
//ud variable used in Updating and Deleting Record
if (txtprocode.Text != "" && txtproname.Text != "" && txtprotype.Text != "" && txtbrand.Text != "" && txtquantity.Text != "" && txtmeasurements.Text != "" && txtprice.Text != "")
{
cmd = new SqlCommand(#"INSERT INTO [dbo].[Product]([ProductCode],[ProductName],[ProductType],[Brand],[Quantity],[Measurements],[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)");
con.Open();
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Measurements", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
//Reading data
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["ProductType"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["Brand"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["Quantity"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["Measurements"].ToString();
dataGridView1.Rows[n].Cells[6].Value = item["Price"].ToString();
}
}
else
{
MessageBox.Show("Please provide details!");
}
}
cmd.ExecuteNonQuery(); - this statement gets highlighted and error is shown:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteNonQuery: Connection property has not been initialized.
Can anyone assist me with this? or tell me what changes to makes ?
Thank you :)
You need to set the Connection property of the SqlCommand object - or pass it as an argument to the SqlCommand constructor.
Also: please use the using (...) { ... } blocks - as illustrated here: SqlCommand.
You're creating the SqlConnection and the SqlCommand - but you're never connecting the two....
The command needs a connection - I'd recommend setting it when creating the command:
SqlCommand cmd = new SqlCommand("Your SQL query here", con);
You forgot to set the SqlCommand Connection property.
You can do cmd.Connection = con;
or
cmd = new SqlCommand(#"INSERT INTO [dbo].[Product]([ProductCode],[ProductName],[ProductType],[Brand],[Quantity],[Measurements],[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)", con);
Correct template is (Microsoft Docs):
private static void ExecuteNonQueryParameters(string connectionString, string queryString, Action<SqlCommmand> sqlCommandAction)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
sqlCommandAction();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
}
Usage:
...
ExecuteNonQueryParameters(#"INSERT INTO
[dbo].[Product](
[ProductCode],
[ProductName],
[ProductType],
[Brand],
[Quantity],
[Measurements],
[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)",
cmd=>{
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Measurements", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
});
...
Use:
string CS = ConfigurationManager.ConnectionString["<ConnectionString located in web.config file or Create it in web.config file>"].connectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
query = "INSERT INTO Product(ProductCode, ProductName, ProductType, Brand, Quantity, Measurements, Price)
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)";
using(SqlCommand cmd = new SqlCommand(query,con))
{
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Meter", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
By the way you error was in #Meter and #Measurements
In SQL query you write it #Meter and in
cmd.Parameters.AddWithValue("#Measurements");
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");
}
I want to reload the updated record in gridview but its not working. Grid View reloads after i insert any new record but not reloads after i update the record. Although the record is saved in the Database and when i restart the application, the gridview load the updated record. I don't know why it's not reloading data when i update but reload data when i insert new record, Although i am calling the same function as i called in insertion
Here is Insert Code
private void InsertEmployee()
{
if (tbName.Text != "" && mtbCNIC.Text != "" && cBoxBloodGroup.SelectedIndex != -1 && cBoxMaritialStatus.SelectedIndex != -1 && tbAddress.Text != "" && tbFatherName.Text != "" && cBoxGender.SelectedIndex != -1 && tbPerAddress.Text != "")
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(emp_id),0)+1 FROM EMP_Master", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();
{
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO EMP_Master (emp_id , emp_name,emp_fathername,emp_nic,emp_gender,emp_contact,emp_dob,emp_bloodgroup,emp_maritialstatus,emp_address,emp_per_address,emp_picture)VALUES(#emp_id , #emp_name,#emp_fathername,#emp_nic,#emp_gender,#emp_contact,#emp_dob,#emp_bloodgroup,#emp_maritialstatus,#emp_address,#emp_per_address,#emp_picture)", con))
{
//con.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#emp_id", tbID.Text);
cmd1.Parameters.AddWithValue("#emp_name", tbName.Text);
cmd1.Parameters.AddWithValue("#emp_fathername", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#emp_nic",mtbCNIC.Text);
//string tbMaskCNIC = mtbCNIC.Text;
//tbMaskCNIC = tbMaskCNIC.Replace("-","");
//cmd1.Parameters.AddWithValue("#emp_nic", int.Parse(tbMaskCNIC));
cmd1.Parameters.Add("#emp_gender", SqlDbType.VarChar, 50);
cmd1.Parameters["#emp_gender"].Value = cBoxGender.SelectedItem;
cmd1.Parameters.AddWithValue("#emp_contact", tbContact.Text);
cmd1.Parameters.AddWithValue("#emp_dob", dtpBirth.Value.Date);
cmd1.Parameters.AddWithValue("#emp_bloodgroup",cBoxBloodGroup.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_maritialstatus",cBoxMaritialStatus.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#emp_per_address", tbPerAddress.Text);
cmd1.Parameters.AddWithValue("#emp_picture", SaveImage());
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Has been Saved Successfully !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGridView();
ResetForm();
tbName.Focus();
}
}
}
}
else
{
MessageBox.Show("All Fields are Mandatory !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
tbName.Focus();
}
//catch (Exception)
//{
// MessageBox.Show("Something is wrong");
//}
}
and here is the update code
private void UpdateEmployee()
{
try
{
//if (tbName.Text != "" && mtbCNIC.Text != "" && tbContact.Text != "" && tbAddress.Text != "" && tbFatherName.Text != "" && cBoxBloodGroup.SelectedIndex != -1 && cBoxGender.SelectedIndex != -1 && tbPerAddress.Text != "" && dtpBirth.Text != "")
//{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
{
using (SqlCommand cmd1 = new SqlCommand("UPDATE EMP_Master SET emp_name=#emp_name,emp_fathername=#emp_fathername,emp_nic=#emp_nic,emp_gender=#emp_gender,emp_contact=#emp_contact,emp_dob=#emp_dob,emp_bloodgroup=#emp_bloodgroup,emp_maritialstatus=#emp_maritialstatus,emp_address=#emp_address,emp_per_address=#emp_per_address,emp_picture=#emp_picture WHERE emp_id=#emp_id", con))
{
con.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#emp_id", tbID.Text);
cmd1.Parameters.AddWithValue("#emp_name", tbName.Text);
cmd1.Parameters.AddWithValue("#emp_fathername", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#emp_nic", mtbCNIC.Text);
cmd1.Parameters.Add("#emp_gender", SqlDbType.VarChar, 50);
cmd1.Parameters["#emp_gender"].Value = cBoxGender.SelectedItem;
cmd1.Parameters.AddWithValue("#emp_contact", tbContact.Text);
cmd1.Parameters.AddWithValue("#emp_dob", Convert.ToDateTime(dtpBirth.Value.ToString()));
cmd1.Parameters.AddWithValue("#emp_bloodgroup", cBoxBloodGroup.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_maritialstatus", cBoxMaritialStatus.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#emp_per_address", tbPerAddress.Text);
cmd1.Parameters.AddWithValue("#emp_picture", SaveImage());
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Has been Updated Successfully !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGridView();
ResetForm();
tbName.Focus();
}
}
}
//}
//else
//{
// MessageBox.Show("All Fields are Mandatory !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// tbName.Focus();
//}
}
catch (Exception)
{
throw;
}
}
Here is the Method for for Loading data to gridview
private void FillGridView()
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT * FROM EMP_Master", con))
{
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
}
}
}
Is there's something wrong with my code ? i guess not because data is inserted and updated in to the database . help me please
You need to fill your grid view with data. And I think you should add binding in FillGridView() method:
private void FillGridView()
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT * FROM EMP_Master", con))
{
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
gridView.DataSource = dt;
gridView.Update();
}
}
}
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.