Insert Currency into Access Database C#? - c#

I want to insert currency in access data I am using datatype currency with general number format here is my c# code
decimal price = decimal.Parse(vCCY_Rate.ToString(), System.Globalization.NumberStyles.Currency);
SCmd.Parameters.AddWithValue("#CCY_Rate", price);
nReturnValue = (int)SCmd.ExecuteNonQuery();
where vCCY_Rate is double but this always store 1 in database and some time 0
can you tell me how to store currency in database access using c#. I have data of precion 6 that is also mentioned in currency datatype with general format and presicion
SQL Command
OleDbConnection SConnection = new OleDbConnection();
OleDbCommand SCmd = new OleDbCommand();
Save_Main("INSERT into tblOprCurrency_Rate ([CCY_ID_From], [CCY_ID_To] , [CCY_Active] , [CCY_Rate] ,[CCY_Chr]) VALUES (? , ? , ? ,? ,? )", cmbCurrency_From.SelectedItem.Value, cmbCurrency_To.SelectedItem.Value, Convert.ToDouble(txtCCY_Rate.Text), chkCCY_Active.Checked, 0, hdfSr_ID.Value);
public int Save_Main(string vQuery, string vCCY_ID_From, string vCCY_ID_To, double vCCY_Rate, bool bCCY_Active, int vIsUpdate, string vCCY_SrNo)
{
sErrorCode = "";
int nReturnValue = -1;
try
{
decimal price = (decimal)vCCY_Rate;
// decimal price = decimal.Parse(vCCY_Rate.ToString(), System.Globalization.NumberStyles.Currency);
SCmd.CommandText = vQuery;
SCmd.CommandType = CommandType.Text;
SCmd.Parameters.AddWithValue("#CCY_ID_From", vCCY_ID_From);
SCmd.Parameters.AddWithValue("#CCY_ID_To", vCCY_ID_To);
SCmd.Parameters.AddWithValue("#CCY_Rate", price);
SCmd.Parameters.AddWithValue("#CCY_Active", bCCY_Active);
SCmd.Parameters.AddWithValue("#CCY_Chr", Convert.ToDouble(0));
SCmd.Parameters.AddWithValue("#CCY_SrNo", vCCY_SrNo);
SCmd.Connection = SConnection;
SCmd.CommandTimeout = pSQL_CommandTimeOut;
SDataAdapter.SelectCommand = SCmd;
SConnection.Open();
nReturnValue = (int)SCmd.ExecuteNonQuery();
}
CCY_Rate is currency datatype and generat format with 6 decimal places in ACCESS

You are using named parameters in your code & positional parameters in your query - Rate & Active are in the wrong order.
Also you have added 6 parameters, but only 5 positional (question mark) parameters.

Related

How to convert null value to default(float) 0.0 value and should save that default value into MYSql version(6.0.11-alpha-community)

Dynamically reading the excel data (from filezilla) and saving into mysql version (6.0.11-alpha-community)
I'm using the stored procedure (to capture the Excel.csv data) and save it into mysql version (6.0.11-alpha-community)
but while I'm executing or saving the data into mysql I'm getting this error:
In the above image 2021070701.csv and 2021070801.csv are reading and saving into mysql is fine because there is no null data in the excel file (particular cell).
when it reach the execution to this file 2021070201.csv I'm getting the "Format exception error"
The 2021070201.csv(excel) data look like this format:
(2021070201.csv excel data and blue highlighted cells are float values and the cells contains null data)
This is what I written logic to read the excel data and saving into mysql
else if (mpType.Equals("Indices", StringComparison.InvariantCultureIgnoreCase))
{
MAE_Repo.InsertNseIndicesPrice("Usp_tbl_Intraday_NseIndicesPrice", 0, Convert.ToInt32(res[0]), res[1], Convert.ToSingle(res[2]),
Convert.ToSingle(res[3]), Convert.ToSingle(res[4]), Convert.ToSingle(res[5]), Convert.ToSingle(res[6]),
Convert.ToSingle(res[7]), Convert.ToSingle(res[8]), Convert.ToSingle(res[9]), Convert.ToSingle(res[10]),
Convert.ToDateTime(res[11]), res[12], timeStamp, filename);
}
And this is what I written the SP logic:
Public static void InsertNseIndicesPrice(String ProcName, int ipID, int ipIndextoken, string ipSymbol, float ipCLOSE,
float ipOPEN, float ipHigh,float ipLow, float ipVolume, float ipVALUE, float ipprev_close, float ipCHANGE, float ipPer_Change,
DateTime ipUpdtime, string ipFlag, DateTime ipCreatedOn, string ipFileName)
{
con.Open();
MySqlCommand cmdSel = new MySqlCommand(ProcName, con);
cmdSel.CommandType = System.Data.CommandType.StoredProcedure;
cmdSel.Parameters.AddWithValue("#IPID", 0);
cmdSel.Parameters.AddWithValue("#IPIndextoken", ipIndextoken);
cmdSel.Parameters.AddWithValue("#IPSymbol", ipSymbol);
cmdSel.Parameters.AddWithValue("#IPCLOSE", ipCLOSE);
cmdSel.Parameters.AddWithValue("#IPOPEN", ipOPEN);
cmdSel.Parameters.AddWithValue("#IPHigh", ipHigh);
cmdSel.Parameters.AddWithValue("#IPLow", ipLow);
cmdSel.Parameters.AddWithValue("#IPVolume", ipVolume);
cmdSel.Parameters.AddWithValue("#IPVALUE", ipVALUE);
cmdSel.Parameters.AddWithValue("#IPprev_close", ipprev_close);
cmdSel.Parameters.AddWithValue("#IPCHANGE", ipCHANGE);
cmdSel.Parameters.AddWithValue("#IPPer_Change", ipPer_Change);
cmdSel.Parameters.AddWithValue("#IPUpdtime", ipUpdtime);
cmdSel.Parameters.AddWithValue("#IPFlag", ipFlag);
cmdSel.Parameters.AddWithValue("#IPCreatedOn", ipCreatedOn);
cmdSel.Parameters.AddWithValue("#IPFileName", ipFileName);
cmdSel.Parameters.AddWithValue("#OPType", 1);
MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
And this is my stored Procedure in mysql
DELIMITER $$
USE `marketprice_nse`$$
DROP PROCEDURE IF EXISTS `Usp_tbl_Intraday_NseIndicesPrice`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `Usp_tbl_Intraday_NseIndicesPrice`(IN IPID BIGINT, IN IPIndextoken INT, IN IPSymbol VARCHAR(20), IN IPCLOSE FLOAT,
IN IPOPEN FLOAT, IN IPHigh FLOAT,IN IPLow FLOAT, IN IPVolume FLOAT, IN IPVALUE FLOAT,IN IPprev_close FLOAT, IN IPCHANGE FLOAT, IN IPPer_Change FLOAT,
IN IPUpdtime DATETIME, IN IPFlag VARCHAR(1), IN IPCreatedOn DATETIME, IN IPFileName VARCHAR(30),IN OPType INT)
BEGIN
IF (OPType = 1)-- Insert
THEN
-- IF (SELECT 1 FROM tbl_intraday_nseindicesprice WHERE FileName = IPFileName) = 0
-- THEN
-- BEGIN
INSERT INTO tbl_Intraday_NseIndicesPrice (ID, Indextoken, Symbol, `CLOSE`, `OPEN`, High, Low, Volume, `VALUE`, prev_close, `CHANGE`,
Per_Change, Updtime, Flag, CreatedOn, FileName) VALUES (IPID, IPIndextoken, IPSymbol, IPCLOSE, IPOPEN, IPHigh, IPLow, IPVolume,
IPVALUE, IPprev_close, IPCHANGE, IPPer_Change, IPUpdtime, IPFlag, IPCreatedOn, IPFileName);
-- END;
-- END IF;
ELSEIF (OPType = 2)-- Check FileName availability
THEN
SELECT * FROM tbl_intraday_nseindicesprice WHERE FileName=IPFileName;
END IF;
END$$
DELIMITER ;
I tried different ways like
Single.Parse() Method
float.Parse() Method
Convert.ToSingle() Method
these methods are not solved the format exception
How can I save the default value(0.0) into mysql with out any format exception?
OK based on the comments this is the answer:
Instead of writing Convert.ToSingle(res[6]) you can write Convert.ToSingle(res[6] ?? "0.0"). Then if the value of res[6] is null, the string "0.0" will be used converted to a single instead.
If you need to worry about various locales having period or comma as decimal separator, you could simply use "0" as the default (which will also convert to a 0.0 float), or create a string having the local decimal separator
string defaultFloatValue = (0.0F).toString();
and use it instead of the "0.0" literal.

How is azerbaijan characters insert in mssql?

I have a program written using C# and wpf.I want to insert azerbaijan character to Mssql from this program but '?' character is showing in row. Mssql datatype is nvarchar(50). How am I do?
public void YeniLiderEkle(string LiderAdi, string sifre, int Admin){
BakuBusCenterDBDataContext db = new BakuBusCenterDBDataContext();
Liderler liderler = new Liderler();
liderler.AdiSoyadi = LiderAdi;
string a1 = StringReplace(LiderAdi.Replace(" "," ").Replace(" "," ").Trim().ToLower()).Split(' ')[0];
string l=a1.Split('_')[1].Substring(0,1);
liderler.KullaniciAdi = a1.Split('_')[0]+l;
db.Liderlers.InsertOnSubmit(liderler);
db.SubmitChanges();
}
And true word "sdəhr" but showing "sd?hr" from Mssql
For inserting varchar values you should wrap them with ' like 'Hello', for nvarchar you should also use N before the wrapping ' chars: N'Yaşasın Azerbaycan'.

How to fix the length for the string builder string in Winform C#?

In my project, I'm using a StringBuilder to create a table in RichEditBox. But in my column the data value is differ from each other. So it looks like shuffled data. But my excepted output is to be perfectly fix the length for the data in table. I can see the table as properly completed in my output .
Can anyone say how to fix the length to the string in StringBuilder in C#?
My code:
Connection();
try
{
string Today = "Student Test Mark Details";
string Line = "----------------------------------";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd = new SqlCommand("select ExaminationName, ExaminationCenter, ExaminationDate, Subjects, MarkObtained, Total, Percentage, Grade from StudentMarksHistory where StudentCode='" + ICBEStudentCode.Text + "' and ExaminationName='" + TBExaminationName.Text + "' and ClassName='" + ICBEClassSection.Text + "' and Remark='Record Saved'", cs);
StringBuilder paragraph = new StringBuilder();
SqlDataReader dr = cmd.ExecuteReader();
paragraph.Append(Today).Append("\t\n");
paragraph.Append(Line).Append("\t\n\n\n\n\n");
paragraph.Append("ExamName").Append("\t");
paragraph.Append("ExamCenter").Append("\t");
paragraph.Append("ExamDate").Append("\t");
paragraph.Append("Subject").Append("\t\t\t");
paragraph.Append("Mark").Append("\t");
paragraph.Append("Total").Append("\t");
paragraph.Append("Percentage").Append("\t");
paragraph.Append("Grade").Append("\n\n");
while (dr.Read())
{
DateTime DateName = Convert.ToDateTime(dr["ExaminationDate"]);
string subject = dr["Subjects"].ToString().Trim();
//int Len = subject.Length;
//subject = subject.ToString().PadRight(50 - Len, ' ');
paragraph.Append(dr["ExaminationName"].ToString()).Append("\t");
paragraph.Append(dr["ExaminationCenter"].ToString()).Append("\t");
paragraph.Append(DateName.ToString("dd/MM/yyyy")).Append("\t");
paragraph.Append(subject);
paragraph.Append(' ', 15 - subject.Length);
//paragraph.Append(subject.PadRight(100));
paragraph.Append(dr["MarkObtained"].ToString()).Append("\t");
paragraph.Append(dr["Total"].ToString()).Append("\t");
paragraph.Append(dr["Percentage"].ToString()).Append("\t");
paragraph.Append(dr["Grade"].ToString()).Append("\n");
}
string Notes = "************[ Minimum Pass Mark is 35 ]*************";
paragraph.Append(" ").Append("\n\n\n\n");
paragraph.Append(Notes).Append("\r\n");
dr.Close();
cs.Close();
}
RTBMessage.Text = paragraph.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Results expceted:
Student Test Mark Details
----------------------------------
ExamName ExamCenter ExamDate Subject Mark Total
Class Test 1 Room No1 24/05/2013 STOREDPROCEDURE 97 404
Class Test 1 Room No1 25/05/2013 DOTNET 86 404
Class Test 1 Room No1 26/05/2013 TAMIL 80 404
Class Test 1 Room No1 23/05/2013 SOCIAL 80 404
Class Test 1 Room No1 27/05/2013 COMPUTER 61 404
************[ Minimum Pass Mark is 35 ]*************
Do not use TABs to align the column but use Composite Formatting through AppendFormat method of the StringBuilder
Just as an example for your first column.
I suppose that ExamName should be inserted left aligned in a column large 20 characters.
You could write
paragraph.AppendFormat("{0:20}","ExamName");
while for the Grade column right aligned in a 6 char space
paragraph.AppendFormat("{0:-6}\r\n", "Total");
Of course this kind of alignement is dependent on the kind of font used in the RichTextBox. If you use a proportional font there is no way to align this text in the way you like.
At the end I really suggest you to use a DataGridView instead
As the lenght of your data is very fluctuating, do not add tabs "\t", this will not work if some data is longer than tabsize
You can use the
String.PadRight(Int32, Char)
Method if you know your maximum expected data lenght.
Remember the usage: the first parameter describes the total lengt not the number of characters to fill
http://msdn.microsoft.com/en-us/library/66f6d830(v=vs.71).aspx

Odd Oracle Error

I'm having a small issue with an Oracle command, given below:
command.CommandText = "SELECT ID, NAME, RATING, LENGTH, STARTTIME FROM SCHEDULE WHERE ID=301 AND ROWNUM=1 AND SCHEDULE.STARTTIME <= SYSDATE ORDER BY STARTTIME DESC;";
It runs perfectly well in Oracle SQL Developer, returning exactly what I need, but in C#, i get the following error:
ORA-06550: line 1, column 186:
PLS-00103: Encountered the symbol "," when expecting one of the following:
. ( * # % & = - + < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec as between || indicator multiset member
submultiset
Can anyone see any issues with it, or anything that is illegal within C#?
EDIT: Execution code:
command.Connection = conSQL;
using (IDataReader reader = command.ExecuteReader())
{
do
{
int count = reader.FieldCount;
while (reader.Read())
{
for (int i = 0; i < count; i++)
{
string setting = reader.GetName(i).ToString();
object value = reader.GetValue(i);
** Data assigned to variables here, hidden due to length of code**
** Follows pattern: object.property(reader.name) = reader.value **
}
}
} while (reader.NextResult());
}
dot not put ; at the end of the command, that's a command line tool convention, not part of sql proper (sqlplus also uses / as terminator for instance)
Name and Id are both special keywords in Oracle SQL. Try:
SELECT "ID", "NAME"...
Remove the trailing semi-colon on the SQL statement.
Share and enjoy.

Help with linq to sql insert error

I have a database table with all columns to allow nulls for testing purposes. Between all of my columns I have int, varchar or bit datatypes. When I try to submit the form I get the following error message:
Value was either too large or too small for an Int32.
Here is the code:
using (storeDataContext db = new storeDataContext())
{
db.Dealerssses.InsertOnSubmit(new Dealersss
{
AppFName = txtFName.Text,
AppLName = txtLName.Text,
AppTitle = ddlTitles.SelectedItem.Text,
AppPhone = Convert.ToInt32(txtPhone.Text),
AppEmail = txtEmail.Text,
AppAddress = txtAddress.Text,
AppCity = txtCity.Text,
AppState = txtState.Text,
AppZip = Convert.ToInt32(txtZip.Text),
BusName = txtBusName.Text,
BusCA = Convert.ToInt32(txtBusResale.Text),
BusContact = txtBusContact.Text,
BusDBA = txtDBA.Text,
BusEIN = Convert.ToInt32(txtBusEIN.Text),
BusEmail = txtBusEmail.Text,
BusFax = Convert.ToInt32(txtBusFax.Text),
BusMonth = ddlMonthStart.SelectedItem.Text,
BusNumEmployees = Convert.ToInt32(txtBusEmployees.Text),
BusPhone = Convert.ToInt32(txtBusPhone.Text),
BusYear = int.Parse(txtYearStart.Text),
Active = false
});
db.SubmitChanges();
};
Int32.MaxValue is 2,147,483,647, which is only 10 digits long.
Your values are too large for an Int32.
Your Phone, Fax, ZIP, and EIN fields should be strings (NVARCHARs), not numbers.
I'm betting it's the value for your phone number fields. Int32 is a 4 byte integer with a max value of 2147483647. Most phone numbers will overflow that.
My guess is it is on your phone #'s Int32's have a value of:
-2,147,483,648 to 2,147,483,647
So if you have the phone # of 517111111 (5,171,111,111), you are too large.
You should use varchar/char for phone numbers.

Categories

Resources