Can you fix my problem? I try to insert data in table database oracle, but the data take from session array.
this code controller to insert data
int[] NoId = (int[])Session["Id"];
string[] NamaBarang = (string[])Session["namaBarang"];
string[] HargaSatuan = (string[])Session["harga"];
string[] JumlahBarang = (string[])Session["jumlah"];
string[] HargaTotal = (string[])Session["total"];
string[] Diskon = (string[])Session["disc"];
string[] DPP = (string[])Session["Dpp"];
string[] PPN = (string[])Session["Ppn"];
MPMISTAX_DTLMASUK itemA = new MPMISTAX_DTLMASUK();
itemA.KD_PPN = "2";
itemA.KDUNIT = Kategori;
itemA.KODE_SUPP = "M2Z";
itemA.NOFAK = nomorFaktur;
itemA.KDFAK = kodeFaktur;
itemA.VKODECABANG = KodeMain;
item.TAHUN = TanggalFak.Year;
itemA.RETUR = "";
itemA.NMBRG = NamaBarang[0];
itemA.HRGSAT = HargaSatuan[0];
itemA.NPWP = npwpPenjual;
itemA.NODOK = "-";
dbContext.MPMISTAX_DTLMASUK.Add(itemA);
dbContext.SaveChanges();
I try using that code, but its error. I Hope you can help my problem. Thank you
What is the datatype of
itemA.NMBRG?
if it's long please convert the NamaBarang[0] to long datatype before assigning. Like
itemA.NMBRG = (long)NamaBarang[0];
Hope this helps!!
You are trying to assign string to a feild which is of type long .Parse the string to long for feild NMBRG.
itemA.NMBRG = (long)NamaBarang[0];
Related
I work on an online search project
I want to make a search textbox that works like: if I want to search about a book that Joe wrote it with title my book and publisher is tia.
I type in the search: joe my book tia or tia jo book >
so I will get a result for it.
tia is from a table in SQL database
joe is from a table in SQL database
my book is from a table in SQL database
can somebody help me?
You can easily accomplish that if you add another column, that will contain concatenated data from other three columns, to your data table (in your database) and then make a search in that column.
writer title publisher search_column
joe my book tia joe my book tia
Then, you can make SQL query to search by that column with LIKE
example with ExecuteReader.
var query = "select * from my_table where 1 = 1 " + filterQuery;
Create parameters:
public static SqlParameter AddSqlParameter(string parameterName, object value)
{
var p = new SqlParameter(parameterName, value);
return p;
}
List<SqlParameter> sqlParameters = new List<SqlParameter>();
var filterQuery = "";
this will split your search input by spaces
string[] words = searchInput.Split(' ');
loop through your search phrases and add one parameter for each phrase found:
for (int i = 0; i < words.Count; i++) {
sqlParameters.Add(AddSqlParameter("#p" + i.ToString(), words[i]));
filterQuery = filterQuery + " AND search_column LIKE " + "#p" + i.ToString();
}
add your search query and parameters to ExecuteReader:
public static List<T> ExecuteReader<T>(string commandText, List<SqlParameter> parameters) where T : new()
{
List<T> output = new List<T>();
using (SqlConnection con = new SqlConnection(mySetting.ConnectionString))
using (SqlCommand cmd = new SqlCommand(commandText, con))
{
cmd.Parameters.AddRange(parameters.ToArray());
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
T t = new T();
for (int i = 0; i < rdr.FieldCount; i++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(rdr.GetName(i));
if (prop != null)
{
prop.SetValue(t, rdr.GetValue(i) is DBNull ? null : rdr.GetValue(i), null);
}
}
output.Add(t);
}
return output;
}
}
}
call your ExecuteReader like this:
var result = ExecuteReader<myClass>(query, sqlParameters );
If you have further questions, just ask.
i have to read rows of data from an excel file which has only a column and then i have to save the rows in a table in database .
In my project i have to use ClosedXML .dll .
I have search but i couldn't find an example .
Can you please help me?
Thanks
For the ClosedXML part, you can refer to the documentation at https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data
private static void Main()
{
List<String> categories;
List<String> companies;
ExtractCategoriesCompanies("NorthwindData.xlsx", out categories, out companies);
// Do something with the categories and companies
}
private static void ExtractCategoriesCompanies(string northwinddataXlsx, out List<string> categories, out List<string> companies)
{
categories = new List<string>();
const int coCategoryId = 1;
const int coCategoryName = 2;
var wb = new XLWorkbook(northwinddataXlsx);
var ws = wb.Worksheet("Data");
// Look for the first row used
var firstRowUsed = ws.FirstRowUsed();
// Narrow down the row so that it only includes the used part
var categoryRow = firstRowUsed.RowUsed();
// Move to the next row (it now has the titles)
categoryRow = categoryRow.RowBelow();
// Get all categories
while (!categoryRow.Cell(coCategoryId).IsEmpty())
{
String categoryName = categoryRow.Cell(coCategoryName).GetString();
categories.Add(categoryName);
categoryRow = categoryRow.RowBelow();
}
// There are many ways to get the company table.
// Here we're using a straightforward method.
// Another way would be to find the first row in the company table
// by looping while row.IsEmpty()
// First possible address of the company table:
var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address;
// Last possible address of the company table:
var lastPossibleAddress = ws.LastCellUsed().Address;
// Get a range with the remainder of the worksheet data (the range used)
var companyRange = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed();
// Treat the range as a table (to be able to use the column names)
var companyTable = companyRange.AsTable();
// Get the list of company names
companies = companyTable.DataRange.Rows()
.Select(companyRow => companyRow.Field("Company Name").GetString())
.ToList();
}
EDIT: The below only gets you a populated datatable. You'll then need to load that datatable into your database. You don't say which database this is, but for SQL Server you would use the SqlBulkCopy class (see definition, which also has an example).
Late to the party, but try this:
public static DataTable GetDataTableFromExcel(string path, string sheetname = "", bool hasHeader = true)
{
using (var workbook = new XLWorkbook(path))
{
IXLWorksheet worksheet;
if (string.IsNullOrEmpty(sheetname))
worksheet = workbook.Worksheets.First();
else
worksheet = workbook.Worksheets.FirstOrDefault(x => x.Name == sheetname);
var rangeRowFirst = worksheet.FirstRowUsed().RowNumber();
var rangeRowLast = worksheet.LastRowUsed().RowNumber();
var rangeColFirst = worksheet.FirstColumnUsed().ColumnNumber();
var rangeColLast = worksheet.LastColumnUsed().ColumnNumber();
DataTable tbl = new DataTable();
for (int col = rangeColFirst; col <= rangeColLast; col++)
tbl.Columns.Add(hasHeader ? worksheet.FirstRowUsed().Cell(col).Value.ToString() : $"Column {col}");
Logger("started creating datatable");
rangeRowFirst = rangeRowFirst + (hasHeader ? 1 : 0);
var colCount = rangeColLast - rangeColFirst;
for (int rowNum = rangeRowFirst; rowNum <= rangeRowLast; rowNum++)
{
List<string> colValues = new List<string>();
for (int col = 1; col <= colCount; col++)
{
colValues.Add(worksheet.Row(rowNum).Cell(col).Value.ToString());
}
tbl.Rows.Add(colValues.ToArray());
}
Logger("finished creating datatable");
return tbl;
}
}
and call like this:
var datatable = GetDataTableFromExcel(fileName, sheetName);
If you're using (the excellent and free in its basic form) LinqPad, you can inspect the datatable using datatable.Dump();
My code below won't compile, the error message saying that PDM is not declared. I'm trying to call a SQL Server stored procedure from vb.net, and the code I have seems to match similar examples that I've found. Why doesn't the PDM part work for me?
Public Function ReturnPointSource(ByVal PlantName)
Dim TempList = New ArrayList
Dim sqlDR As SqlClient.SqlDataReader = PDM.Data.SqlHelper.ExecuteReader(GLOBALS.ConnectionString, "sp_readLocation")
If sqlDR.HasRows Then
While sqlDR.Read()
Dim Loc As New Location
Loc.strFID = sqlDR(0)
Loc.strFeature = sqlDR(1).ToString
Loc.intPlantNo = sqlDR(2).ToString
Loc.strPlantName = sqlDR(3).ToString
Loc.strMunicipality = sqlDR(4).ToString
Loc.strRegion = sqlDR(5).ToString
Loc.strOperator = sqlDR(6).ToString
Loc.strDistrict = sqlDR(7).ToString
Loc.strWatercourse = sqlDR(8).ToString
Loc.dblCapacity = sqlDR(9).ToString
Loc.dblPopulation = sqlDR(10).ToString
Loc.strOwnership = sqlDR(11).ToString
Loc.strOwnerClass = sqlDR(12).ToString
Loc.strCofNum = sqlDR(13).ToString
Loc.strComments = sqlDR(14).ToString
Loc.dblLatitude = sqlDR(15).ToString
Loc.dblLongitude = sqlDR(16).ToString
Loc.strSource_Point = sqlDR(17).ToString
Loc.intSeverity = sqlDR(18).ToString
Loc.dblSafe_buffer_distance_m = sqlDR(19).ToString
TempList.Add(Loc)
End While
End If
Return TempList
End Function
If you've taken that directly from an example then PDM would be something that they have defined themselves. It's not something that is part of the .NET Framework. I'm guessing that PDM is the author and SqlHelper is a class in their PDM.Data namespace.
If you want to get a data reader then you create a SqlCommand and then call ExecuteReader on it. That is what that PDM.Data.SqlHelper will be doing internally.
I am inserting data in the sql server.Here is the code:
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Int;
param[0].Value = "BSE";
formObjSqlConnection.SQLConnection.Executes("LPExch..DeleteVarMargin", param);
foreach (BseVar objBseVar in objListNseData)
{
currentIndex++;
param = new SqlParameter[10];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Char;
param[0].Value = "BSE";
param[1] = new SqlParameter();
param[1].ParameterName = "#Symbol";
param[1].SqlDbType = SqlDbType.Char;
param[1].Size = 10;
param[1].Value = objBseVar.Symbol;
param[2] = new SqlParameter();
param[2].ParameterName = "#Series";
param[2].SqlDbType = SqlDbType.Char;
param[2].Value = "EQ";
param[3] = new SqlParameter();
param[3].ParameterName = "#SecurityVar";
param[3].SqlDbType = SqlDbType.SmallMoney;
param[3].Value = objBseVar.SecurityVar;
param[4] = new SqlParameter();
param[4].ParameterName = "#IndexVar";
param[4].SqlDbType = SqlDbType.SmallMoney;
param[4].Value = 0;
param[5] = new SqlParameter();
param[5].ParameterName = "#VarMargin";
param[5].SqlDbType = SqlDbType.SmallMoney;
param[5].Value = objBseVar.IndexVar;
param[6] = new SqlParameter();
param[6].ParameterName = "#AdhocMargin";
param[6].SqlDbType = SqlDbType.SmallMoney;
param[6].Value = objBseVar.SecurityVar - objBseVar.IndexVar;
param[7] = new SqlParameter();
param[7].ParameterName = "#VarMarginRate";
param[7].SqlDbType = SqlDbType.SmallMoney;
param[7].Value = objBseVar.IndexVar;
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateOrAddCashVarMarginBSE", param);
if (Convert.ToInt32(1 / progressChange * currentIndex) <= 100)
objImportMaster.UpdateProgressBar(Convert.ToInt32(1 / progressChange * currentIndex));
}
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateCashVarMarginBSEScripNo");
Is there any other way i can insert the data in the database.The problem is that database is taking too much time to insert the data.Also i am updating the progressbar in other UI.
Is that the reason for slow insertion?
Can we use any other way to insert data.?
Right now you are sending every insert one at a time. That's slow. If you can change the database, look up table valued parameters and pass a table to your function so you can send all the records just once.
If you have direct access to a table, you can also use bulk copy.
If you are trying to insert many records then consider using bulk copy, it is quite fast.
An example is available here.
I have a dataset and I'm adding new rows, and then I'm updating the database behind the dataset using the following command:
DataSetReasons ds = new DataSetReasons();
DataSetReasonsTableAdapters.Data_Tracker_RcodeTableAdapter dta = new DataSetReasonsTableAdapters.Data_Tracker_RcodeTableAdapter();
DataSetReasons.Data_Tracker_RcodeDataTable GRX =
new DataSetReasons.Data_Tracker_RcodeDataTable();
DataRow rowx = GRX.NewRow();
rowx[0] = 111;
rowx[1] = 28;
rowx[2] = "C";
rowx[3] = 12;
rowx[4] = "C";
rowx[5] = 16;
rowx[6] = TextBox2.Text;
GRX.Rows.Add(rowx); //<--- adding the row
dta.Update(GRX); //<-- updating the DB
now everything works fine, except that I want to put the update command in a separate button. when I do so, the DB update are not happening.
any idea?
Solved, I was missing the "static" word before defining the data table.
Many thanks to whoever passed on this question.