Data in Oracle Database table is not being fully updated - c#

I want to update an Oracle Database table after querying the table and applying an encryption function to the retrieved data from some fields. However, my code (below) does not work correctly:
private void button2_Click(object sender, EventArgs e)
{
using (OracleConnection conn = new OracleConnection(oradb))
conn.Open();
OracleCommand select = new OracleCommand("select empno,FNAME,LNAME from employee", conn);
OracleDataReader reader = select.ExecuteReader();
Int64 vempno = 0;
String fnameValue = "";
String lnameValue = "";
String afterConcatfname = "";
String afterConcatlname = "";
if (reader.HasRows)
{
while (reader.Read())
{
vempno = reader.GetInt64(0);
fnameValue = reader.GetString(1);
lnameValue = reader.GetString(2);
REA rea = new REA();
afterConcatfname = rea.Encrypt(fnameValue, rea.GenerateKey());
afterConcatlname = rea.Encrypt(lnameValue, rea.GenerateKey());
}
reader.Close();
}
OracleCommand update = new OracleCommand("update employee set fname =:fname, lname =:lname where empno =:empno", conn);
OracleParameter fname = new OracleParameter("fname", afterConcatfname);
OracleParameter lname = new OracleParameter("lname", afterConcatlname);
OracleParameter empno = new OracleParameter("empno", vempno);
update.Parameters.Add(fname);
update.Parameters.Add(lname);
update.Parameters.Add(empno);
update.ExecuteNonQuery();
}
I don't receive any error but the program encrypts only the last record with all the encrypted values. I want to encrypt every row.

"I dident receive any error ,but the program encrypts only the last record by all the encrypted values "
That's the logic of your code. Basically, what you are doing is this:
loop
read one row
encrypt one row
end loop
update one row
" I want to encrypt row by row "
So you need to move the update logic into the loop, so that it is executed for each row.
A better solution would be to replace row-by-row processing with a set operation, but that's a different question.

Related

How to fill up datagridview cells based on other cell IDs?

I have an Access database that has name ID-s in a column and I filled up the first column with those ID-s (38, 51, 88) and what I want to do is based on those ID-s I want to fill up the last selected column with some other data that are in the Access database but in another table.
For example, ID 38 would give me a price or a name in that row.
I tried it a lot of times but couldn't find a solution and I don't know If I have to use SQL for this or something else.
I got the needed SQL code but I don't know how to use it for the datagridview.
I have used something like that to fill up combo boxes like this:
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = "the connection string";
connection.Open();
string query2 = "SELECT Name From Names";
command.CommandText = query2;
OleDbDataReader reader2 = command.ExecuteReader();
while (reader2.Read())
{
Combobox1.Items.Add(reader2["Name"].ToString());
}
connection.Close();
And now I think I should make an if statement where it checks if the 38 ID is in the DataGridView, then fill the other cell with the value in the same row of the Access table.
Do you want to populate the datagridview with the corresponding Price and Name that from another table?
Here is a demo you can refer to.
private void btnSetPriceName_Click(object sender, EventArgs e)
{
string constr = #"connection string";
// create sql string
StringBuilder strSQL = new StringBuilder();
strSQL.Append("select Price, Name from PriceName where ");
for(int i = 0;i< dataGridView1.Rows.Count - 1;i++)
{
// get Id from string, like "38/1/R"
string Id = dataGridView1.Rows[i].Cells[0].Value.ToString().Split('/')[0];
if (i == 0)
strSQL.Append("Id = " + Id);
else
strSQL.Append("or Id = " + Id);
}
using (OleDbConnection conn = new OleDbConnection(constr))
{
OleDbCommand cmd = new OleDbCommand (strSQL.ToString(), conn);
conn.Open();
try
{
OleDbDataReader reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
int rowindex = 0;
while (reader.Read())
{
// Set Price/Name column value
dataGridView1.Rows[rowindex].Cells["Price"].Value = reader[0].ToString().Trim();
dataGridView1.Rows[rowindex].Cells["Name"].Value = reader[1].ToString().Trim();
rowindex++;
}
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Saving a textfile into sql and sending it to FTP server

I have created a textfile programmatically and I saved it into a folder and now I need to save it into a table inside a database(I have already created the table)and after that fill a checkbox with those textfiles and send them to an FTP server.
Is that possible? If so how can I start doing it/what should I do?
Here is the code for creating the textfile and the code to the create the table. If you have any question about the code feel free to ask.
var numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
using (StreamWriter writer = new StreamWriter("C:\\Users\\HP8200\\Desktop\\Faturas Teste\\" +numfatura + ".txt"))
{
string numcont = _transaction.PartyFederalTaxID;
double numenc = _transaction.BillToPartyID;
DateTime data = _transaction.CreateDate;
double valor = _transaction.TotalAmount;
int zona = transaction.UnloadPlaceAddress.AddressID;
string zona2 = transaction.UnloadPlaceAddress.AddressLine2;
double quantidade = transaction.Details.Count;
string bonus = "0";
string valorStr = valor.ToString(CultureInfo.InvariantCulture);
writer.WriteLine($"{numcont};{numenc};{numfatura};{data:dd/MM/yyyy};{valorStr};{zona};");
foreach (ItemTransactionDetail detail in transaction.Details)
{
var item = MyApp.DSOCache.ItemProvider.GetItem(detail.ItemID, MyApp.SystemSettings.BaseCurrency);
double taxRate = MyApp.DSOCache.TaxesProvider.GetTaxRateFromTaxableGroupID(detail.TaxableGroupID, "PRT", "CON");
string barcode = item.BarCode;
var preconet = detail.TaxIncludedPrice;
var precoantesdisc = detail.UnitPrice;
string preconetStr = preconet.ToString(CultureInfo.InvariantCulture);
string precoantesdiscStr = precoantesdisc.ToString(CultureInfo.InvariantCulture);
writer.WriteLine($"{barcode};{taxRate};{precoantesdiscStr};{preconetStr};{quantidade};{bonus}");
}
} // create the text file
SqlConnection conn = new SqlConnection(#"Data source = 2c4138928627\Sage ; Database=ARMINDOData ; User Id=sa ; Password=sage2008+");
SqlCommand command = new SqlCommand("IF OBJECT_ID('UXFaturas', 'U') IS NULL CREATE TABLE UXFaturas(Faturas char(250));", conn);
conn.Open();
SqlCommand insertCommand = new SqlCommand("INSERT INTO UXFaturas(Faturas) VALUES (*.txt)", conn);
command.ExecuteNonQuery();
MessageBox.Show("saved"); // create the table and insert the textfile
Create a stored procedure that takes in two parameters fileName and fileContent and then store it inside your UXFaturas table.
CREATE PROC USP_InsertFile(#fileName nvarchar(200),#fileContent nvarchar(max))
AS
BEGIN
INSERT INTO UXFaturas VALUES(#fileName,#fileContent)
END
Here i am assuming that you UXFaturas table only has two columns.
Now you can simple call this stored procedure from your C# ADO code and pass in the right parameters.
using (SqlConnection conn = new SqlConnection(#"Data source = 2c4138928627\Sage ; Database=ARMINDOData ; User Id=sa ; Password=sage2008+"))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "USP_InsertFile";
command.Parameters.AddWithValue("#fileName",fileName);
command.Parameters.AddWithValue("#fileContent",fileContent);
command.ExecuteNonQuery();
}

Editing a datatable and sending it back to a database

With my program I have a datatable that gets populated with records fetched from a database. This is displayed in a datagrid view and when a cell is clicked it loads all the values into textboxes. When a save button is clicked it will then save the textbox values back into the datatable. However how can I send this datatable back to the database and have it update the records?
Here is my code to load the records:
indexRow = e.RowIndex;
DataGridViewRow row = dgv_ReturnSearch.Rows[indexRow];
tb_editFirstName.Text = row.Cells[1].Value.ToString();
tb_editLastName.Text = row.Cells[2].Value.ToString();
tb_editAge.Text = row.Cells[3].Value.ToString();
tb_editPostCode.Text = row.Cells[4].Value.ToString();
tb_editMobNum.Text = row.Cells[5].Value.ToString();
tb_editEmail.Text = row.Cells[6].Value.ToString();
tb_editAllergies.Text = row.Cells[7].Value.ToString();
tb_editDOB.Text = row.Cells[8].Value.ToString();
tb_editGender.Text = row.Cells[9].Value.ToString();
Here is my code to save them
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
newDataRow.Cells[1].Value = tb_editFirstName.Text;
newDataRow.Cells[2].Value = tb_editLastName.Text;
newDataRow.Cells[3].Value = tb_editAge.Text;
newDataRow.Cells[4].Value = tb_editPostCode.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
However this doesn't actually update the database, only the local datatable. When it is loaded again all the changes revert.
Thanks
To load a gridview with data from the database you'll need to use DataTable and DataAdapter then bind the grid. it should look something like this:
private void CustomersBindGrid()
{
using (SqlConnection con = new SqlConnection(mycon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM Customers";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
con.Close();
}
}
Try updating the database directly:
private void SaveEdits_Click()
{
using (SqlConnection con = new SqlConnection(mycon))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE Customers set firstname= #FN , lastname= #LN , age = #AG , postcode= #PC where CustomerID = #CustID";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#CustID", cid);
cmd.Parameters.AddWithValue("#FN", tb_editFirstName.Text);
cmd.Parameters.AddWithValue("#LN", tb_editLastName.Text);
cmd.Parameters.AddWithValue("#AG", tb_editAge.Text);
cmd.Parameters.AddWithValue("#PC", tb_editPostCode.Text);
cmd.ExecuteNonQuery();
}
}
CustomersBindGrid();
MessageBox.show("Information Updated!");
}
}
You need to edit this update command to your columns in the database and get a way to read the customer id so the condition actually work and update the database.
In your posting, you don't write, how your client is developed...
Normally, this would be done with a SQL update command.
Therefore (in the Microsoft universe) the SqlClient (System.Data.SqlClient Namespace) can be used.
As soon as the user press the save button, you overtake the relevant textbox.text values in variables, change datatypes if necessary, generate an SQL update string to update the data on your SQL server.
Example SQL update string:
Update TableName set ColumnName1Text = 'some text', ColumName2Integer = 12, ColumnName.... = ... where ColumnNameKey = KeyToDatatable
Then you submit the SQL command (SQL update string) to the SQL server via SqlClient (SqlCommand).
But therefore you need a unique key for the where clause (in the example KeyToDatatable) so that only the row with the key is updated.
The key normally is queried from the DataTable (with the other fields) to show the data (in your grid) and then taken over to the update command (can be "hided" from the user, that don't has to know the key).
Well I managed to fix it by doing:
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
dt.Rows[indexRow]["first_name"] = tb_editFirstName.Text;
dt.Rows[indexRow]["last_name"] = tb_editLastName.Text;
dt.Rows[indexRow]["age"] = tb_editAge.Text;
dt.Rows[indexRow]["postcode"] = tb_editPostCode.Text;
dt.Rows[indexRow]["mobile_num"] = tb_editMobNum.Text;
dt.Rows[indexRow]["email"] = tb_editEmail.Text;
dt.Rows[indexRow]["allergies"] = tb_editAllergies.Text;
dt.Rows[indexRow]["DOB"] = tb_editDOB.Text;
dt.Rows[indexRow]["gender"] = tb_editGender.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
Instead of what I was doing before, now it works perfectly and any changes are saved back to the database.

sql query to show data from price between two columns C#

EDIT: I am not able to format my code below, if any one can fix it.
I am new to sql queries and still learning.
Table Name: CommissionSetupTable.
I want to display #Paisa if gross_amount is between the range of #FromRate and #ToRate
Below is my code:
string paisa;
private void load_commission_setup()
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Database.sdf;Persist Security Info=False");
conn.Open();
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
gross_amount = double.Parse(purchaseBillTableDataGridView[10, rowindex].Value.ToString());
// Gross Amount is between the ranges of FromRate and ToRate.
cmd = new SqlCeCommand("SELECT Paisa FROM CommissionSetupTable WHERE='" + gross_amount.ToString() + "' BETWEEN #FromRate AND #ToRate;", conn);
rdr = cmd.ExecuteReader();
if (rdr == null)
{
}
else
{
while (rdr.Read())
{
paisa = rdr["Paisa"].ToString();
}
rdr.Close();
cmd.Dispose();
}
}
finally
{
conn.Close();
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
purchaseBillTableDataGridView[11, rowindex].Value = paisa;
}
}
The correct syntax to use here is the following
cmd = new SqlCeCommand(#"SELECT Paisa FROM CommissionSetupTable
WHERE #gross BETWEEN FromRate AND ToRate;", conn);
Notice that the two field names should not be prefixed with #, otherwise they will be considered parameters placeholders.
And now, before executing the command, add the parameter for the #gross placeholder
cmd.Parameters.Add("#gross", SqlDbType.Decimal).Value = gross_amount;
I don't know what is the exact datatype of the columns FromRate and EndRate, but
note that you should use the correct datatype for your parameter. Do not pass a string and expect the database engine do the conversion for you. (or worse concatenate your value to the rest of the sql using ToString()). This is always wrong also if sometime the database engine could understand your values.
EDIT
Also, following your comments below, it appears that this line is wrong
int rowindex = purchaseBillTableDataGridView.Rows.Count - 1;
If your DataGridView has the property AllowUserToAddRow set to True then you want to use
int rowindex = purchaseBillTableDataGridView.Rows.Count - 2;
because the first line points to the empty row added to the DataGridView for inserting a new record.

Categories

Resources