SERVER A: public string connStr = "Data Source=PH-09-5336;Initial Catalog=InventoryDB;Integrated Security=True";
SERVER B: public string connWIP = "Data Source=PWODU-COGNOSDB3;Initial Catalog=BI_SOURCE;
I have this method of inserting records to InventoryDB.DBO.FG_FILLIN from excell file.
Select records from BI_SOURCE.dbo.ODU_WIP_PI then update the null records(item Number) on InventoryDB.DBO.FG_FILLIN if its serialnumber is match on BI_SOURCE.dbo.ODU_WIP_PI serialnumber.
Problems:
I have tried to updated 13000 of records and it takes 5 minutes to be updated.
I need to update the new inserted record InventoryDB.DBO.FG_FILLIN that has only itemnumber that have null records.
But in my code it loops and update again all records in InventoryDB.DBO.FG_FILLIN
I really stack in this problem.
-------------------------------------INSERT RECORDS----------------------------------------
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("Insert into dbo.FG_FILLIN Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=" + filepath1 + ";HDR=YES','SELECT * FROM [" + Sheetname1 + "$]')", conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
txtsheet1.Text = string.Empty;
txtpath1.Text = string.Empty;
txtpath1.Focus();
MessageBox.Show("FILL IN Mass Upload Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
txtsheet1.Text = string.Empty;
txtpath1.Text = string.Empty;
txtpath1.Focus();
}
finally
{
if (conn.State == ConnectionState.Open) cmd.Connection.Close();
conn.Close();
}
}
---------------------------------SELECT UPDATE -----------------------------------
public void Update()
{
using (SqlConnection conn = new SqlConnection(connWIP))
{
try
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select WIP_serialNumber, WIP_ItemID from BI_SOURCE.dbo.ODU_WIP_PI", conn))
{
DataTable data = new DataTable();
dAd.Fill(data);
using (SqlConnection conn2 = new SqlConnection(connStr))
{
conn2.Open();
try
{
foreach (DataRow recordFromServerA in data.Rows)
{
using (SqlCommand dCmd = new SqlCommand("update [dbo].[FG_FILLIN] SET ItemNumber=#ItemNumber where SerialNumber=#SerialNumber", conn2))
{
dCmd.Parameters.AddWithValue("#ItemNumber", recordFromServerA["WIP_ItemAlias"]);
dCmd.Parameters.AddWithValue("#SerialNumber", recordFromServerA["WIP_serialNumber"]);
dCmd.ExecuteNonQuery();
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn2.State == ConnectionState.Open) conn2.Close();
}
}
}
MessageBox.Show("All Records Updated Successfully!");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
#endregion
If I've understood your problem correctly you might be able to speed up the update process considerably by just executing a single SQL statement, rather than looping through each row individually.
How about this? After you've loaded your records into table A (FG_FILLIN), create an SQL UPDATE statement that uses a join from table A onto table B where the ItemNumber field in table A is null. Something like this should do it:
UPDATE [dbo].[FG_FILLIN]
SET ItemNumber = table2.WIP_ItemID
FROM [dbo].[FG_FILLIN] INNER JOIN BI_SOURCE.dbo.ODU_WIP_PI as table2
ON [dbo].[FG_FILLIN].SerialNumber = table2.WIP_SerialNumber
WHERE [dbo].[FG_FILLIN].ItemNumber IS NULL
another thing,
you could also wrap you stuff into a
using(var scope = new TransactionScope())
{
stuff
scope.Complete();
}
to make it a transaction
Related
I'm getting this error on phpMyAdmin
mysqli_connect(): (08004/1040): Too many connections
The only script that is using this DB:
public static bool checkIp(string ip)
{
Console.WriteLine("CHECKIP");
try
{
string sql = " SELECT * FROM `Ip tables` ";
MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
con.Close();
return false;
}
catch(SqlException exp)
{
throw new InvalidOperationException("Error", exp);
}
}
Does this code close the connection correctly or something is wrong?
EDIT:
I added this block after the catch block
finally
{
if(con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
Any better way to write the code? Would finaly block still run if return is executed?
You should put your query in a using statement like this:
string conString= "host=hostname;user=username;password=password;database=database;"
using (MySqlConnection con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM `Ip tables`";
using (MySqlDataReader dr = com.ExecuteReader())
{
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
}
}
}
This will automatically close the connection without having to state con.Close()
I want to know how to delete a row from a table in the database using listview and button.
My code
private void deleteitems()
{
//DELETE FROM Tbl_Cashier WHERE RecpieId = #RecpieId AND IngredientId = #IngredientId
string query = "delete from Tbl_Cashier where Cashier_ID = '" + listView1.SelectedIndices+"' ";
using (SqlConnection connection = new SqlConnection(connectionString1))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.Remove(listView1.SelectedIndices);
command.ExecuteNonQuery();
connection.Close();
}
MessageBox.Show("You will see the new data with your next restart of the application", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
I am getting this error:
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Additional information: The SqlParameterCollection only accepts non-null SqlParameter type objects, not SelectedIndexCollection objects.
When you mentioned "a Row", we can assume that you only wish to delete one row from your database table.
Another important assumption is that the first column of your listview contains the Cashier_ID of your database table.
Thus, here's what you need to do:
private void DeleteSelectedItemFromListView() {
var cashierId = listView1.FocusedItem.Text;
string query = "delete from Tbl_Cashier where Cashier_ID=#id;";
using (SqlConnection con = new SqlConnection(connectionString1)) {
try {
con.Open();
using (SqlTransaction trans = con.BeginTransaction()) {
using (SqlCommand com = new SqlCommand(query, con, trans)) {
com.Parameters.AddWithValue("id", cashierId);
var should_be_one = com.ExecuteNonQuery();
if (should_be_one == 1) {
trans.Commit();
} else {
trans.Rollback();
throw new Exception("An attempt to delete multiple rows was detected");
}
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
} finally {
con.Close();
}
}
}
However, if you wish to delete several items from your listview (multiple selected items), that's a different story.
You should remove this line:
command.Parameters.Remove(listView1.SelectedIndicies)
And then you should loop over the selection-indicies and fire a query for each selected item, like this:
private void deleteitems()
{
using (SqlConnection connection = new SqlConnection(connectionString1))
{
connection.Open();
foreach(var index in listView1.SelectedIndicies)
{
// Modify this to get the 'cashier_id' from you listView at the specified row index...
// You should also consider using a prepared query...
string query = "delete from Tbl_Cashier where Cashier_ID = '" + index +"' ";
using (SqlCommand command = new SqlCommand(query, connection))
{
// consider checking the return value here if the delete command was successful
command.ExecuteNonQuery();
}
}
}
MessageBox.Show("You will see the new data with your next restart of the application", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
** not tested **
So the problem is, when execute, it show successful update, n if i debug again, it really did delete, but when i rebuild solution or go to view datatable, it show didnt deleted the row, how i enable to delete the datarow?
private void Update_btn_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string deletequery = " DELETE FROM StudentBook WHERE BookREF = #Book_Ref ";
using (SqlCommand command = new SqlCommand(deletequery, con))
using (SqlDataAdapter adapter3 = new SqlDataAdapter(command))
{
con.Open();
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#Book_Ref", Book_Ref.SelectedItem.ToString());
command.ExecuteNonQuery();
adapter3.Update(dt);
dt.AcceptChanges();
MessageBox.Show("update successful");
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
Scan_lbl.Text = string.Empty;
Scan_lbl.Select();
}
You may want to change your MessageBox to give you more feedback:
using (SqlConnection con = new SqlConnection(connectionString))
{
string deletequery = " DELETE FROM StudentBook WHERE BookREF = #Book_Ref ";
using (SqlCommand command = new SqlCommand(deletequery, con))
{
using (SqlDataAdapter adapter3 = new SqlDataAdapter(command))
{
con.Open();
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#Book_Ref", Book_Ref.SelectedItem.ToString());
int rowsAffected = command.ExecuteNonQuery();
adapter3.Update(dt);
dt.AcceptChanges();
if (rowsAffected > 0) {
MessageBox.Show(String.Format("{0} rows deleted.", rowsAffected));
}
else
{
MessageBox.Show(String.Format("no rows deleted, bookref: {0}", Book_Ref.SelectedItem.ToString()));
}
}
}
con.Close();
}
I want to Insert auto generate number show in textbox when form is loaded (like 000000001) in database that not define primary key and if table number found 0 then it increment every time when form open by user to entry data. Please help me how to do it. I am using C#.
Thanks
its working , but I need to from table filed.
public void RetriveWorkRequestNo ()
{
try
{
string query = "SELECT IDENT_CURRENT('WorkRequests')";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlCommand cmdwr = new SqlCommand(query, conn);
SqlDataReader reader = cmdwr.ExecuteReader();
while (reader.Read())
{
int value = int.Parse(reader[0].ToString()) + 1;
textWorkRequestNo.Text = value.ToString("0000000000");
textWorkRequestNo.ReadOnly = true;
}
}
catch (Exception)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
Finally I have done it using Sequence in MS SQL Server 2012
private int RetriveWorkRequestID()
{
try
{
string query = "SELECT NEXT VALUE FOR sqWorkRequests";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
using (SqlCommand cmd = new SqlCommand(query, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int value = int.Parse(reader[0].ToString());
string date = DateTime.Now.ToString("yyMM");
WorkRequestID = Convert.ToInt32(date.ToString() + value.ToString("000"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return WorkRequestsID;
}
I have the following code in C#-
private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();
if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}
I am getting the value of the variable enqid from a combobox on my Windows form.The contents of the combobox are retrieved from the database. On form load, the combobox displays the first enquiryID retrieved from the database. When I run my program the data reader skips the loop. However if I select a different enquiry in the combobox, the data reader works properly
It seems that you've forgot to associate Command with the Connection:
// SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this
// have SQL readable
cmd.CommandText =
#"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = #prm_Id";
// use parametrized queries
cmd.Parameters.AddWithValue("#prm_Id", enqid);
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}
And never, never after write code alike
catch (Exception)
{
}
which means "just ignore all the errors and continue".