I'm trying to a simple insert list of rows from a DataGridView to a database.
I have made a checkedbox that upon checked, the item will be added to the DataGridView. Now i'm attempting to do the INSERT part. This what I have come up so far:
try
{
string strAppointment = "SELECT appointmentID FROM APPOINTMENT WHERE appointmentID=#searchappointmentID";
SqlCommand cmdAppointment = new SqlCommand(strAppointment, connection);
cmdAppointment.Parameters.AddWithValue("#searchappointmentID", txtAppointmentID.Text);
connection.Open();
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
string firstColumn = dataPrescription[0, dataPrescription.CurrentCell.RowIndex].Value.ToString();
string strMedications = "SELECT medicationID FROM MEDICATION WHERE medicationName= ('" + firstColumn + "')";
SqlCommand cmdMedications = new SqlCommand(strMedications, connection);
SqlDataReader readMedications = cmdMedications.ExecuteReader();
if (readMedications.Read())
{
string getDrugID = readMedications["medicationID"].ToString();
string strPrescriptions = "INSERT INTO PRESCRIPTION (appointmentID, medicationID, quantity) " +
"VALUES (#insertAppointment, "
+ getDrugID + ", "
+ dataPrescription.Rows[i].Cells["columnQuantity"].Value + ");";
SqlCommand cmdPrescriptions = new SqlCommand(strPrescriptions, connection);
cmdPrescriptions.Parameters.AddWithValue("#insertAppointment", txtAppointmentID.Text);
prescriptionsResult = cmdAppointment.ExecuteNonQuery();
}
readMedications.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
connection.Close();
}
Right now it giving me this error: "There is already an open DataReader associated with the command which must be closed first". I don't know what I've done wrong
Try this: (initialize the datareader)
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
string firstColumn = dataPrescription[0, dataPrescription.CurrentCell.RowIndex].Value.ToString();
string strMedications = "SELECT medicationID FROM MEDICATION WHERE medicationName= ('" + firstColumn + "')";
SqlCommand cmdMedications = new SqlCommand(strMedications, connection);
SqlDataReader dr = new SqlDataReader(); //Insert this line in your code
SqlDataReader readMedications = cmdMedications.ExecuteReader();
It looks like you're trying to execute a command using a connection that's occupied with the reader, and I would look at that as being the problem. Instead of trying to execute the insert inside the reader, try reading the data to a collection and closing the reader, then iterating the connection to make you're updates.
Related
https://ibb.co/DkKdpnL
This is the code im using in the Database controller. Im sure there is nothing wrong with this code but i keep on getting the error message when I select a date from the Monthly calender Picker.
{
SqlDataReader reader;
SqlCommand command;
Collection<StockItem> items;
try
{
DateTime input;
DateTime.TryParse(date, out input);
command = new SqlCommand("SELECT * FROM StockItem WHERE DATEDIFF(day, stockItemExpiryDate,'" + input.ToString() + "') >= 0 ORDER BY stockItemShelfNumber", cnMain);
cnMain.Open();
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
items = new Collection<StockItem>();
if (reader.HasRows)
{
while (reader.Read())
{
StockItem item = new StockItem();
item.expiryDate = reader.GetDateTime(1).ToShortDateString();
item.shelfNumber = reader.GetString(2);
item.numberInStock = reader.GetInt32(3) + "";
item.productRef = reader.GetInt32(4) + "";
SqlConnection connection = newConn();
SqlCommand command2 = new SqlCommand("SELECT productPackaging FROM Product WHERE productID =" + item.productRef + ";", connection);
connection.Open();
command2.CommandType = CommandType.Text;
SqlDataReader reader2 = command2.ExecuteReader();
String description = "";
if (reader2.HasRows)
{
reader2.Read();
description = reader2.GetString(0);
}
reader2.Close();
connection.Close();
item.productRef = description;
items.Add(item);
}
}
reader.Close();
cnMain.Close();
this.items = items;
return items;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
cnMain.Close();
Console.WriteLine(ex.ToString());
}
return null;
}```
From the error, I assume the exception is being raised by
item.expiryDate = reader.GetDateTime(1).ToShortDateString();
Logically, field 1 (The second column) in your StockItem table isn't a Date/Time. I'd check your table, and if you're sure that's right, maybe use reader.GetValue(1) instead, and see what you get.
I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.
This question already has an answer here:
how to i search if there is a same id in a database?
(1 answer)
Closed 6 years ago.
private void Add_Box_Click(object sender, EventArgs e)
{
string phoneNumber;
if (string.IsNullOrWhiteSpace(Id_Box.Text))// To check if the Id_box is empty or not
{
MessageBox.Show("Please Enter Your ID");// need to enter ID in order to save data
}
///////////////////////////////////////////check the Extension Box////////////////////////////////////////////////////////////////////////////////////
else
{
if (string.IsNullOrWhiteSpace(Ext_Box.Text))
{
phoneNumber = Phone_Box.Text;// if it is empty then it will only show the phone number
}
else
{
phoneNumber = Phone_Box.Text + "," + Ext_Box.Text; // show the phone number and the extension if there is something in the extension
}
///////////////////////////////////////////////////////////Save it to the Database///////////////////////////////////////////////////////
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Contact_List(Id, Name, Adress1, Adress2, City, Province, Postal_Code, Phone, Email)VALUES('" + Id_Box.Text + "','" + Name_Box.Text + "','" + Adress1_Box.Text + "','" + Adress2_Box.Text + "','" + City_Box.Text + "','" + Province_Box.Text + "','" + Code_Box.Text + "','" + phoneNumber + "','" + Email_Box.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Information Added", "Confirm");
/////////////////////////////////////Show new set of data after insert a new data/////////////////////////////////////////////////////////////
SqlCeCommand cmd2 = new SqlCeCommand("Select * from Contact_List;", con);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmd2;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
////////////////////////////////Empty The Box/////////////////////////////////////////////////////////////////////////////////////////////////
Id_Box.Text = String.Empty;
Name_Box.Text = String.Empty;
Adress1_Box.Text = String.Empty;
Adress2_Box.Text = String.Empty;
City_Box.Text = String.Empty;
Province_Box.Text = String.Empty;
Code_Box.Text = String.Empty;
Phone_Box.Text = String.Empty;
Ext_Box.Text = String.Empty;
Email_Box.Text = String.Empty;
}
}
This code will store Id, name, etc to the database. But when there is a same Id, i want to delete it. When i delete it both of the same Id will be deleted and i don't want that so is there anyway to check duplicate before it store it to the database?
I want to do something like this if possible :
if ( the values in id column == to the Id_textBox) {
MessageBox.Show("Duplicate ,PLease enter anotherId")
}
Possible?
Before executing your INSERT SQL statement, try running the SQL int ContactCount = (int)cmd.ExecuteScalar("SELECT COUNT(*) FROM CONTACT_LIST WHERE Id = '" + Id_Box.Text + "'")
If ContactCount > 0 then you can do the DELETE your suggesting.
Can I also recommend that you use a SQL UPDATE instead of DELETEing and INSERTing the same record.
Also, read-up on SQL Injection attacks. Building a SQL statement, like you're doing here, using the values input by a user leaves you exposed to that type of vulnerability.
First of all, like in all these answers: Don't use string concatenation but parametrized queries to prevent SQL-injection.
For your problem:
You can either do a
string query = "SELECT count(*) from ContactList Where id = #id";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = (int)cmd.ExecuteScalar();
if count > 0 the id already exists.
Or you can do a
string query "IF NOT EXISTS(SELECT count(*) from ContactList Where id = #id) INSERT INTO ContactList(Id, ...) VALUES(#id, ...)";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = cmd.ExecuteNonQuery();
count will then contain the number of rows affected, ie 0 if the value already existed, or 1 if it did not exist, but was newly inserted.
I am having this problem
Input string was not in a correct format.
highlighted to the part of:
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
I am having a hard time figuring out what is the error, can you help me? Thank you very much.
Here is my set codes:
private void displayNavigate()
{
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
double dTotal = 0;
try
{
for (int nRow = 0; nRow <= grdDetails.Rows.Count - 1; nRow++)
{
dTotal = dTotal + Convert.ToDouble((grdDetails.Rows[nRow].Cells["Amount"].Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
lblTotal.Text = string.Format("{0:#,##00.00}", dTotal);
}
//================================================================================
//================================================================================
private void DisplayOrder(int nOrderNo)
{
try
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText = "SELECT " +
"B.OrderNo, B.OrderDate, A.CustomerNo, " +
"A.CustomerName, A.CustomerAddress, B.PurchaseOrderNo, B.AgentName, B.Status " +
"FROM Customers AS A, Orders AS B " +
"WHERE A.CustomerNo = B.CustomerNo " +
"AND B.OrderNo ='" + nOrderNo + "'";
SqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
txtOrderNo.Text = dr["OrderNo"].ToString();
dtpOrderDate.Value = Convert.ToDateTime(dr["OrderDate"].ToString());
txtCustomerNo.Text = dr["CustomerNo"].ToString();
txtCustomerName.Text = dr["CustomerName"].ToString();
txtCustomerAddress.Text = dr["CustomerAddress"].ToString();
txtPONo.Text = dr["PurchaseOrderNo"].ToString();
cboAgentName.Text = dr["AgentName"].ToString();
txtOrderStatus.Text = dr["Status"].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//================================================================================
//================================================================================
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT PackagingOutside, Quantity, Unit, ProductNo, ProductName, ProductSize, PackagingInside, " +
"SellingDiscount, SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
}
when you use Convert.ToInt16 you will get this exception if value does not consist of an optional sign followed by a sequence of digits (0 through 9)
Do a validation for inputs before proceed like below.
int orderNo;
if (int.TryParse(txtOrderNo.Text, out orderNo))
{
DisplayOrder(orderNo);
DisplayOrderDetails(orderNo);
}
Side Note :
don't share the SqlConnection create new instant when you need it and wrap it with using block like below
using (SqlConnection con = new SqlConnection(connectionString))
{
}
Use SQL Parameters
cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = #OrderNo";
cmdSelect.Parameters.AddWithValue("#OrderNo", nOrderNo);
This means that the value in txtOrderNo.Text is not considered an integer. You will get this error if your textbox is empty.
Either check that the textbox contains data, or use the TryParse (http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method
There are two things to consider,
Values entered in the textbox should be an integer in the range of 16 bit, if it can be bigger value, then you have to think of going to long, int32 etc.
Validate the textbox using TryParse() which will tell you whether it has valid value entered.
Newbie here, I am currently creating a tool that will parse a text file "namelist.txt" contains names. my tool will check if each name are already in my database. if not exist it will write to another file "new_name.log".
my code is something like this.
in my query command I used count(*) to return the count
string DBNAME= "SELECT count(*) FROM tbl_namelist WHERE name = '" + name + "'";
conn.Open();
MySqlCommand DBCmd = new MySqlCommand(DBNAME, conn);
MySqlDataReader reader = DBCmd.ExecuteReader();
while (reader.Read())
{
if (reader == 0)
try
{
//label2.Text = reader.GetString(0);
sds.WriteLine("New Name: " + name+ " " + reader.GetString(0));
}
catch (Exception dd)
{
sds.WriteLine("duplicate Name: " + name+ " " + reader.GetString(0));
}
I dont know if i read the correct info "reader.read" to give me an integer output "count".
please assist me thanks.
don't use MySQLDataReader but instead use command's ExecuteNonScalar to fetch single value.
string DBName = "SELECT count(*) FROM tbl_namelist WHERE name = #name";
using (MySqlConnection conn = new MySqlConnection("connectionString Here"))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
comm.CommandText = DBName;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#name", name);
try
{
conn.Open();
int totalCount = Convert.ToInt32(comm.ExecuteScalar());
if (totalCount == 0)
{
sds.WriteLine("New Name: " + name + " " + totalCount);
}
else
{
// when not zero
}
}
catch( MySqlException ex)
{
// error here
}
}
}
use USING-statement and parameterized your query.
count(*) return int and you should change reader.GetString(0) to reader.GetInt32(0) and in
if(reader==0) to if (reader.GetInt32(0)==0) and it will work