I have a small problem regarding the Access Database when it has data inserted.
I have a button that inserts data when it's clicked. Here it is the code:
string[] read = File.ReadAllLines("Harta_Distantelor.txt");
string[] orase = { "Constanta", "Varna", "Burgas", "Istambul", "Kozlu", "Samsun", "Batumi", "Sokhumi", "Soci", "Anapa", "Yalta", "Sevastopol", "Odessa" };
OleDbCommand cmd;
for (int i = 0; i < read.Length; i++)
{
int j = 0;
string[] numbers = read[i].Split(' ');
while (j < read.Length)
{
//cmd = new OleDbCommand("UPDATE Distante SET ID_Port='" + (i + 1) + "', ID_Port_Destinatie='" + (j + 1) + "', Nume_Port_Destinatie='" + orase[j] + "' WHERE Distanta='" + numbers[j] + "' ", conn);
cmd = new OleDbCommand("INSERT INTO [Distante]([ID_Port], [ID_Port_Destinatie], [Nume_Port_Destinatie], [Distanta]) VALUES ('" + (i + 1).ToString() + "', '" + (j + 1).ToString() + "', '" + orase[j] + "', '" + numbers[j] + "')", conn);
cmd.ExecuteNonQuery();
j++;
}
}
The problem is that instead of having something like ID_Port=1, ID_Port_Destinatie=1, Nume_Port_Destinatie="Constanta", ID_Port=1, ID_Port_Destinatie=2, Nume_Port_Destinatie="Varna" and so on, I get this...
https://i.stack.imgur.com/OjMQm.png
The file "Harta_Distantelor.txt" is a matrix that has the distances, so that's why I tried to split every number from a line(string[] numbers = read[i].Split(' ');). I have to mention that [Distanta] data is correctly inserted, but the rest of the data is totally randomly inserted. I tried to figure out where the problem is, but I have no clue. Where is the mistake? What should I try to do in order to have the data showed correctly?
1.) Create a table called HartaDistantelor with columns for ID_Port, ID_Port_Destinatie, and Distanta
2.) Fill the table HartaDistantelor with your matrix values. You may be able to copy and paste directly into Access
3.) Create a table called Orase with columns for ID_Port and Nume_Port
4.) Fill the table Orase with the 13 values from your array. It should look like this:
1 Constanta
2 Varna
3 Burgas
4 ...
5.) Change your code:
OleDbCommand cmd;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
cmd = new OleDbCommand("INSERT INTO Distante (ID_Port, ID_Port_Destinatie, Nume_Port_Destinatie, Distanta) SELECT " + (i + 1).ToString() + ", " + (j + 1).ToString() + ", o.Nume_Port, h.Distanta FROM Orase o JOIN HartaDistantelor h ON h.ID_Port = o.ID_Port WHERE h.ID_Port = i AND h.ID_Port_Destinatie = j", conn);
cmd.ExecuteNonQuery();
}
}
My approach joins records from two tables using ID values that match. I don't think you made any mistake, but used a method with more complexity than was necessary.
Related
So I'm stumped on this problem.
I need to get all the column values of another table (tbladdbenefit) and add them to another table (payrolltable) and insert all the values of the first table into a single cell.
In this case, I'm trying to insert all of the values of column "benefit" to a single cell of "benefit" on the new table, the same thing for "BenefitAmount".
So far I am using Parameters.AddWithValue but to no avail. I have 2 data from the column benefit from the first table but it only shows the record I highlighted. Which is not what I want to do. I want to display and add all the records of my parent table
Any suggestions?
cmd = new SqlCommand("INSERT INTO payrolltable " +
"(Name, " +
"Position, " +
"Honoraria, " +
"Total, " +
"Benefit, " +
"BenefitAmount, " +
"Deduction, " +
"DeductionAmount) " +
"VALUES " +
"(#name, " +
"#position, " +
"#honoraria, " +
"#total, " +
"#benefit, " +
"#benefitamount, " +
"#deduction, " +
"#deductionamount)", con);
cmd.Parameters.AddWithValue("#name", txtfname.Text + " " + txtlname.Text);
cmd.Parameters.AddWithValue("#position" , txtposition.Text);
cmd.Parameters.AddWithValue("#honoraria", txtsalary.Text);
cmd.Parameters.AddWithValue("#total", 323232);
cmd.Parameters.AddWithValue("#benefit", SqlDbType.VarChar);
cmd.Parameters.AddWithValue("#benefitamount", SqlDbType.BigInt);
cmd.Parameters.AddWithValue("#deduction", " ");
cmd.Parameters.AddWithValue("#deductionamount", " ");
for (int i = 0; i < tbladdbenefit.Rows.Count - 1; i++)
{
cmd.Parameters["#benefit"].Value = tbladdbenefit.Rows[i].Cells[1].Value;
cmd.Parameters["#benefitamount"].Value = tbladdbenefit.Rows[i].Cells[2].Value;
}
There are a couple of ways to store multiple values in a column of a database table.
You can store it as CSV (comma separated values) or JSON or XML, But it will have its downside when you want to update this column values or want to query on this table.
Also just refer to this as well.
Sample as requested:
Please follow the sample to help you to understand the concept.
List<string> ls = new List<string>();
for (int i = 0; i < tbladdbenefit.Rows.Count - 1; i++)
{
ls.Add(tbladdbenefit.Rows[i].Cells[1].Value);
}
string csv = string.Join(",", ls);
cmd.Parameters["#benefit"].Value = csv;
I am working on a c# project and in this project, I want to select some data and show in a datagridview but I have data in my database and I have a query of select but when I click the button so I get this type of error this no row at position 0
Here are the screenshots
https://imgur.com/PKvcgY9
https://imgur.com/aeq0weF
https://imgur.com/8AG3LZ4
Here is my code
dataGridView4.Columns.Add("", "Leave Consumed");
dataGridView4.Columns.Add("", "Leave Allaowed");
dataGridView4.Columns.Add("", "Balance");
for (int i = 0; i < dataGridView4.Rows.Count; i++)
{
DataSet ds1211122 = new DataSet();
DataTable dt1211122 = new DataTable();
ds1211122.Tables.Add(dt1211122);
OleDbDataAdapter da1211122 = new OleDbDataAdapter();
da1211122 = new OleDbDataAdapter("SELECT Sum(USERID) FROM [CHECKINOUT] where " +
"[CHECKTYPE]= '" + "I" + "'AND [USERID] = " +
dataGridView4.Rows[0].Cells[1].Value.ToString() + "AND [CHECKTIME] Between #" +
dateTimePicker2.Value.ToString() + "# AND #" +
dateTimePicker1.Value.ToString() + "# Group By [USERID];", VCON);
da1211122.Fill(dt1211122);
int num = 0;
num = Convert.ToInt32(dt1211122.Rows[0][0].ToString());
VCON.Close();
}
My C# application is significantly slower than I would like. The program accesses an Excel sheet and loops through each row on a sheet / does the following:
Collects variables from that row
Creates an SQL query based off those variables
Executes that query
then a reader goes out and puts it in its proper column on that same row.
*Note, each row has 6 different SQL queries/ final numbers that are calculated and input into the sheet, the code below is just showing the first 2 for brevity's sake. The sheet has around 300 rows, so the program is executing 300 * 6= 1,800 SQL queries each time its run. For each one of those 1,800 numbers, the program is accessing the sheet and inputting it into the sheet.
Instead of doing the excelWorksheet.get_Range and inputting the number into the Excel sheet for each number, one at a time, would it be faster to store each number into an array and then go back later and mass dump all of the numbers into the sheet, once all of the queries have been executed and the array is full?
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=WRDXPVSEPIRPT00;DATABASE=Epicor905;Workstation ID=SMEBPPL204TN;Trusted_Connection=true";
try
{
//initiate the connection
conn.Open();
}
catch(SqlException ex)
{
throw new ApplicationException(string.Format("You're not connected to the database, please close the program, re-connect to the network, and try again."), ex);
}
progressBar1.Value = 60;
statusLabel.Text = "Retrieving account balances from database...";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//iterate through each row and pull information
for (int i = 2; i < lastUsedRow + 1; i++)
{
//string iString = Convert.ToString(i);
statusLabel.Text = "Retrieving balances for " + i + " of " + lastUsedRow + " accounts...";
//declare excel sheet range variables
var CompanyVar = excelWorksheet.get_Range("A" + i, "A" + i).Text;
var FiscalYear = excelWorksheet.get_Range("B" + i, "B" + i).Text;
var FiscalPeriod = excelWorksheet.get_Range("C" + i, "C" + i).Text;
var segValue1 = excelWorksheet.get_Range("F" + i, "F" + i).Text;
var segValue2 = excelWorksheet.get_Range("G" + i, "G" + i).Text;
var segValue3 = excelWorksheet.get_Range("H" + i, "H" + i).Text;
int FiscalYearHelper = Convert.ToInt32(FiscalYear);
var FiscalYearPYY = FiscalYearHelper - 1;
//begin filling in CY YTD column
string SQLCode = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
" FiscalPeriod between 1 AND " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
"AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
"AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";
SqlCommand command = new SqlCommand(SQLCode, conn);
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string cyAct = reader["BalanceAmt"].ToString();
if (cyAct == "")
{
goto CYM;
//cyAct = "0.00";
}
var cyAct1 = (float)Convert.ToDouble(cyAct);
int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
double cyAct2 = (cyAct1 * one);
string cyAct3 = cyAct2.ToString("0.##");
excelWorksheet.get_Range("I" + i, "I" + i).Value = cyAct3;
}
}
//end filling in column
//begin filling in CY Month column
CYM:
string SQLCodeMonth = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
" FiscalPeriod = " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
"AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
"AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";
SqlCommand commandMonth = new SqlCommand(SQLCodeMonth, conn);
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = commandMonth.ExecuteReader())
{
while (reader.Read())
{
string cyAct = reader["BalanceAmt"].ToString();
if (cyAct == "")
{
goto APY;
//cyAct = "0.00";
}
var cyAct1 = (float)Convert.ToDouble(cyAct);
int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
double cyAct2 = (cyAct1 * one);
string cyAct3 = cyAct2.ToString("0.##");
excelWorksheet.get_Range("J" + i, "J" + i).Value = cyAct3;
}
}
//end filling in column
//begin filling in Act PY month column
THIS IS NOT A FULL ANSWER, there is not enough space to write this as a comment, do not mark this as an answer its a comment.
Please try to use objects (instances of classes or structs) it will make your programming more efficient and easy to maintain.
for example:
private void UseObjects()
{
List<ExcelObjects> ListOfvarsForQuery = new List<ExcelObjects>();
for (int i = 2; i < lastUsedRow + 1; i++)
{
ExcelObjects obj = new ExcelObjects();
obj.CompanyVar = ws.Cells[i, 1];
obj.FiscalYear = ws.Cells[i, 2];
obj.FiscalPeriod = ws.Cells[i, 3];
obj.segValue1 = ws.Cells[i, 4];
obj.segValue2 = ws.Cells[i, 5];
obj.segValue3 = ws.Cells[i, 6];
ListOfvarsForQuery.Add(obj);
}
string SQLCode = // use the list of ExcelObjects and write a better query.
}
}
struct ExcelObjects
{
public string CompanyVar;
public string FiscalYear;
public string FiscalPeriod;
public string segValue1;
public string segValue2;
public string segValue3;
}
Instead of looping through each row and running a SQL query for each row, I found that it is faster to outer join the table I speak of in my question with another SQL table that has the account balances on it. I'm doing all of it within memory because I've been coding for 3 weeks and I don't have time to learn how to create a temp table in SQL server yet.
try
{
string CSVFilePathName = textBox4.Text;
for (int i = 0; i < CSVFilePathName.Length; i++)
{
if (CSVFilePathName[i] == '\\')
{
CSVFilePathName.Insert(i + 1, "\\");
}
}
if (string.IsNullOrWhiteSpace(textBox4.Text))
{
MessageBox.Show("Please Select a File");
}
else
{
int count = 0;
// your code here
// string CSVFilePathName = #"'" + textBox4.Text + "'";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
for (int f = 0; f < Cols; f++)
{
q = "SELECT * from questions where main_section='" + Fields[0] + "' AND secondary_section='" + Fields[1] + "' AND tert_section='" + Fields[2] + "' AND question='" + Fields[3] + "' AND difficulty='" + Fields[4] + "'";
OleDbCommand cmdn = new OleDbCommand(q, conn);
//MessageBox.Show(q);
object obj = cmdn.ExecuteScalar();
if (obj == null)
{
q = "insert into questions values('" + Fields[0] + "','" + Fields[1] + "','" + Fields[2] + "','" + Fields[3] + "' ,'" + Fields[4] + "')";
OleDbCommand cmdn1 = new OleDbCommand(q, conn);
cmdn1.ExecuteNonQuery();
}
else
{
count++;
}
//MessageBox.Show(Fields[f]);
}
}
// dataGridClients.DataSource = dt;
string msg = "Upload successful\n";
if (count > 0)
{
msg=count.ToString()+" Questions missed due to their duplicates in the database.";
}
MessageBox.Show(msg);
}
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
I am using c# winform to upload a csv file to my ms access db, but it is givig the error "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data." What should do now?
I suggest specifying the table fields in the SQL like
INSERT INTO questions (fieldname1, fieldname2, ...) VALUES (...)
Use parameterized-values rather than writing the values directly in the string. This also allows you to specify the datatype and then the ADO.Net OLE adapter will hopefully handle it appropriately and get the long text inserted with no trouble. Go to Read / Write BLOBs ... for an example inserting BLOBS. The concept and code example are very relevant to inserting Long Text values. It demonstrates how to set up parameters for the query. In your case, use OleDbType.LongVarWChar for the Long Text fields.
I am not able to find what's wrong with the following code. There is a form on which the selected start date and finish date , as well as a button transition to a new form where DataGridView populated the database , it is necessary to conclusions regarding the selected date , but that he does not want to issue ORA- 00933.No "where" all is well.
void renewOtchet()
{
dgvOtchet.Rows.Clear();
OracleCommand ocm = Oracle.DBConneciton.CreateCommand();
ocm.CommandText = "select num, date_start, date_finish, " +
"trim(name_video), price_video, " +
"trim(fam_client), " +
"trim(kind_zal) from video.allData" +
"where date_start >= ('"+ date1 + "', 'DD.MM.YYYY' ) and date_finish <= ('" + date2+ "', 'DD.MM.YYYY') ";
string[] str = new string[7];
OracleDataReader ord = ocm.ExecuteReader();
while (ord.Read())
{
for (int i = 0; i < 7; i++)
{
str[i] = ord[i].ToString();
if (i == 1 || i == 2)
{
str[i] = str[i].Remove(10);
}
}
dgvOtchet.Rows.Add(str);
}
ord.Dispose();
ord.Close();
}
You can try this.
"select num, date_start, date_finish, " +
"trim(name_video), price_video, " + "trim(fam_client), " +
"trim(kind_zal) from video.allData " +
"where date_start >= TO_DATE('"+ date1 + "', 'DD.MM.YYYY' )
and date_finish <= TO_DATE('" + date2+ "','DD.MM.YYYY') ";
string[] str = new string[7];