Check row count and then insert value - c#

I have a form and i have a listbox in it to select multiple values of different dates. but requirement is one date can be booked for 2 users only once 2 users book the date then i just have to remove it from listbox.
I have created 3 tables. One table (table_dates) is just shows the dates in different rows and second table (table_users) is storing users information and third table (table_map) is mapping user with the dates.
How to write a logic to check if selected date is registered by 2 users already?
Please check my c# code below
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO table_users(Name,Email) OUTPUT INSERTED.userId Values (#name,#email)";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
int lastId = (int)cmd.ExecuteScalar();
if (lastVolId > 0)
{
SqlCommand cmd2 = new SqlCommand();
int counter = 0;
string query = "";
foreach (ListItem li in listBox.Items)
{
if (li.Selected)
{
// I need to write some thing here to check if selected date is registered 2 times
query = "INSERT INTO table_map(userId,dateId) VALUES('" + lastId + "','" + li.Value + "')";
cmd2 = new SqlCommand(query, conn);
cmd2.ExecuteNonQuery();
counter++;
}
}
}
else
{
//Error notification
}
}

Does you table_Date has a column for a unique dateID? It is mendatory for operation u want to perform.
What u need to do is Perform a SELECT QUERY to check if it exists twice.
String selectStatent="SELECT * FROM table_Map WHERE dateID = #dateID";
SqlCommand selectCommand = new SqlCommand( selectStatement, connectionString);
int rowCount = selectCommand.ExecuteScalaer();
if( rowCount <= 2)
{
//Proceed
}

Related

Check SQL for Book_Availability before issuing one (BookAvailability-1)

If I put "if, foreach, and else statement under comment //", the program works and Reduces book count by 1 from SQL database. But I want to check IF there is at least 1 available book to give. This code keeps showing me the message in "else" statement if I leave it like this. Help is needed fast, it's my final project, that is needed to be done before 23.07. :(
int book_qty = 0;
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT * FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
}
if (book_qty > 0)
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Issue_book VALUES(" + TextBoxSearchMembers.Text + ",'" + TextBoxMemberName.Text + "','" + TextBoxMemberContact.Text + "','" + TextBoxMemberEmail.Text + "','" + TextBoxBookName.Text + "', '" + DateTimePicker1.Text + "')";
cmd.ExecuteNonQuery();
SqlCommand cmd1 = connection.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName ='" + TextBoxBookName.Text + "'";
cmd1.ExecuteNonQuery();
MessageBox.Show("successful issue");
this.Close();
else
{
MessageBox.Show("Book not available");
}
You are only checking book_qty from the last row in your result set instead of BookAvailability for all rows. You probably want to do something like:
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT BookAvailability FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
var result = cmd2.ExecuteScalar();
book_qty = Convert.ToInt32(result);
You need to make sure that there is only one book with the given bookname available.
In that case just correcting this one line in your code would help as well:
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
to
book_qty = Convert.ToInt32(dr2["BookAvailability"].ToString());
Otherwise you'd need to query SUM(BookAvailability), but the following code would decrease the amount of books for multiple books at once, that wouldn't be good.
Untested code. I don't have your database. Comments and explanation in line.
private void OPCode()
{
try
{
//keep your connections close to the vest (local)
using (SqlConnection connection = new SqlConnection())
//a using block ensures that your objects are closed and disposed
//even if there is an error
{
using (SqlCommand cmd2 = new SqlCommand("SELECT BookAvailability FROM Book_list WHERE BookName = #BookName", connection))
{
//Always use parameters to protect from sql injection
//Also it is easier than fooling with the single quotes etc.
//If you are referring to a TextBox you need to provide what property is
//being accessed. I am not in a WPF right now and not sure if .Text
//is correct; may be .Content
//You need to check your database for correct data type and field size
cmd2.Parameters.Add("#BookName", SqlDbType.VarChar, 100).Value = TextBoxBookName.Text;
//A select statement is not a non-query
//You don't appear to be using the data table or data adapter
//so dump them extra objects just slow things dowm
connection.Open();
//Comment out the next 2 lines and replaced with
//Edit Update
//var returnVal = cmd2.ExecuteScalar() ?? 0;
//if ((int)returnVal > 0)
//*************************************************************
//Edit Update
//*************************************************************
//in case the query returns a null, normally an integer cannot
//hold the value of null so we use nullable types
// the (int?) casts the result of the query to Nullable of int
Nullable<int> returnVal = (int?)cmd2.ExecuteScalar();
//now we can use the .GetValueOrDefault to return the value
//if it is not null of the default value of the int (Which is 0)
int bookCount = returnVal.GetValueOrDefault();
//at this point bookCount should be a real int - no cast necessary
if (bookCount > 0)
//**************************************************************
//End Edit Update
//**************************************************************
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO issue_book VALUES(#SearchMembers etc", connection))
{
//set up the parameters for this command just like the sample above
cmd.Parameters.Add("#SearchMembers", SqlDbType.VarChar, 100).Value = TextBoxSearchMembers.Text;
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd1 = new SqlCommand("UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName = #BoxBookName;", connection))
{
cmd1.Parameters.Add("#BoxBookName", SqlDbType.VarChar, 100);
cmd1.ExecuteNonQuery();
}
MessageBox.Show("success");
this.Close();
}
else
{
MessageBox.Show("Book not available");
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}

How to implement fifo with conditions in C# and SQL Server?

I have selected multiple datarows with same product name, price and quantity and sorted them according to their primary key values in datatable. But when I decrease stock quantity, it decreases from all the rows. I want my code to check stock quantity according to user quantity entered in textbox and decrease it from FIRST ROW ONLY. This is what I have been able to do so far. apologies in advance for bad formatting I am new to programming and stackoverflow.
The data table has columns
Item_Name, Item_Quantity, Item_Price.
Code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stock_recieve where Item_Name like'" + comboBoxitem.Text + "'order by [Bill No] asc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
// DataRow row = dt.Select("Item_Quantity").FirstOrDefault();
dt.Rows[0]["Item_Quantity"]=;
int qty = 0;
string pname = "";
qty = Convert.ToInt32(dr["Item_Quantity"].ToString());
qty = Convert.ToInt32(textBoxqty.Text);
pname = dr["Item_Name"].ToString();
SqlCommand cmd6 = con.CreateCommand();
cmd6.CommandType = CommandType.Text;
cmd6.CommandText = "update stock_recieve set Item_Quantity=Item_Quantity-" + qty + "where Item_Name ='" + pname.ToString() + "'";
cmd6.ExecuteNonQuery();
}
//MessageBox.Show("Record inserted successfully");
}
Just use top 1 on your select query . Also using SQL parameters is very important. Try like:
...
cmd.CommandText = "select TOP 1 * from stock_recieve where Item_Name like #name order by [Bill No] asc";
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value =comboBoxitem.Text;
cmd.ExecuteNonQuery();
...

Check for duplicate entries before insertion (C#.net)

I have a textbox form that students fill out about their general information such as first and last name, city, state, etc. Sometimes a student can't remember if they filled out the form before and it will lead to duplicate entries in the ms-access database. Ideally I would like the code to first search the ms-access database for a matching first name AND last name on the same record before insertion. If there's a record that matches on both the entered first and last name fields then a script would run and say something like, "A matching record already exists, would you like to continue?" Clicking "Yes" would enter the record into a new row, clicking "Cancel" would not enter it into the database at all.
I started this code but I'm not sure if it's the right direction, any guidance would be appreciated, thanks.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
Below is the current code for the submit button.
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(#FName, #LName, #BDay, #Gender, #School, #Grade, #Address, #APT, #City, #State, #Zip, #Email, #Phone, #CellPhone, #ParentFName, #ParentLName, #ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
com.Parameters.AddWithValue("#BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("#Gender", ddlGender.Text);
com.Parameters.AddWithValue("#School", txtSchool.Text);
com.Parameters.AddWithValue("#Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("#Address", txtAddress.Text);
com.Parameters.AddWithValue("#APT", txtApt.Text);
com.Parameters.AddWithValue("#City", txtCity.Text);
com.Parameters.AddWithValue("#State", ddlState.Text);
com.Parameters.AddWithValue("#Zip", txtZip.Text);
com.Parameters.AddWithValue("#Email", txtEmail.Text);
com.Parameters.AddWithValue("#Phone", txtPhone.Text);
com.Parameters.AddWithValue("#CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("#ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("#ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("#ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
// Add your #Fname and #LName parameters here
com.Parameters.AddWithValue("#FName", firstName);
com.Parameters.AddWithValue("#LName", lastName);
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
myReader.Read();
int count = myReader.GetInt32(0);
// return count > 0 or whatever to indicate that it exists
}
}
couple of things:
you can set in your table the first name and last name as 1 primary key (yes it possible in ms-access). this way you will NEVER get any duplicate records
count(*) is not the best practice with databases.. but since you are dealing with ms-access
using (OleDbDataReader myReader = com.ExecuteReader())
{
// reads the first and only column count(*) and convert it to a number
if (Convert.ToInt16(myReader[0]) > 0)
{
// an entry already exists
}
}
You should use ExecuteScalar when the return value of your query is only a single row with a single column. Of course the OleDbCommand that has parameters placeholders in its command text needs to have also a corresponding Parameters collection
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
int count = Convert.ToInt32(com.ExecuteScalar());
if(count == 0)
{
... record doesn't exist
}
else
{
... you have got count records
}
}
However let me say that this logic is rather weak. What happen if two students have the same First and Last name? What happen if someone mistype the name?. I think that you should require something more unique. Like a SSN or another ID provided by your school. (A Student Number or something alike)
if (txtYear.Text != "")
{
cmd = new SqlCommand("Select YearName from Year where YearName='" + txtYear.Text + "'", ConnOpen());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("Duplicate Values are not valid!!!");
}
else
{
if (Classes.ClassDatabaseConnection.UserMessage("Are you srue you want to Add this Year!!!", "Confirm Updation") == true)
{
string insert = "insert into Year(YearName) values('" + txtYear.Text + "')";
int result = sqlrep.ExecuteNonQuery(insert);
if (result > 0)
{
System.Windows.Forms.MessageBox.Show("Year Added Successfully.", "Information", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
}
dataLoad();
}
}

How to insert date time in database?

I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.

How to check if record exists or not and insert in ms access database in c#

I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#.
OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);
temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("One Record Added");
}
else
{
MessageBox.Show("Record not added");
}
}
catch
{ }
Can Anyone suggest me some code.
Thanks In Advance.
Filter your Select query on the basis of some key . Check if it returns for existence or non-existence of the particular record and do the processing required .
string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
int count = (int)cmd.ExecuteScalar();
if(count >0)
{
//record already exist
}
Modify this line
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);

Categories