SqlDataAdapter Output Variable Question C# - c#

I do not clearly understand how to format the SqlDataAdapter for output variables when working with C#
Error Message:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Code Example (Stored Procedure works fine):
private DataTable updateOrdEodHold(DataTable tb, out string mnpft,
out string authld, out string trd, out string hld, out string extnow)
{
// Start the connection string.
string connstr = ConfigurationManager.ConnectionStrings
["LocalSqlServer"].ConnectionString;
SqlConnection myConn = new SqlConnection(connstr);
// Declare symbol and assign for Errors Catch Exception.
string Symbol = "";
string sqlComm = "dbo.UpdateOrdEodHold";
DataTable HoldVals = new DataTable();
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlComm, myConn);
dataAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
string ticker = (string)Convert.ToString(tb.Rows[0]["Ticker"]);
// update Symbol for Catch ex
Symbol = ticker.ToString();
String company = (string)Convert.ToString(tb.Rows[0]["Company"]);
String avgprofit = (string)Convert.ToString(tb.Rows[0]["AvgProfit"]);
String extdte = (string)Convert.ToString(tb.Rows[0]["ExitDate"]);
dataAdp.SelectCommand.Parameters.Clear();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#ticker",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#ticker"].Value =
(string)ticker.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#company",
SqlDbType.VarChar, 25));
dataAdp.SelectCommand.Parameters["#company"].Value =
(string)company.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#avgpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#avgpft"].Value =
(string)avgprofit.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#mnpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#mnpft"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#authld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#authld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#hld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#hld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#trd",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#trd"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extnow",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#extnow"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extdte",
SqlDbType.VarChar, 15));
dataAdp.SelectCommand.Parameters["#extdte"].Value =
(string)extdte.ToString();
dataAdp.Fill(HoldVals);
mnpft = HoldVals.Rows[0]["MinProfit"].ToString();
authld = HoldVals.Rows[0]["AutoHold"].ToString();
trd = HoldVals.Rows[0]["Trade"].ToString();
hld = HoldVals.Rows[0]["Hold"].ToString();
extnow = HoldVals.Rows[0]["ExitNow"].ToString();
return HoldVals;
}

You need to hold a reference to the Output parameter variable so that you can access the value returned to it using parameter.Value once the adapter has executed the command.
//Create the parameter
SqlParameter parameter = new SqlParameter("#mnpft", SqlDbType.VarChar);
//Set the parameter direction as output
parameter.Direction = ParameterDirection.Output;
sqlCommand.Parameters.Add(parameter);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dataSet);
//Fetch the output parameter after doing the Fill
string outputValue = Convert.ToString(parameter.Value);

Related

C# How to data from two windows form to one database?

i'm working to my lending management system and I want to add data from my database coming to two different windows form.
here's my code to the first windows form.
private void button1_Click(object sender, EventArgs e)
{
if (RequiredEntry() == true)
{
return;
}
try
{
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-79MM8LM;Initial Catalog=lend;Integrated Security=True");
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
cn.Open();
//if (textBox13.Text.Trim() != textBox26.Text.Trim())
if (textBox13. Text != textBox26.Text)
{
string sSQL = "insert into costumerinfo(name,address,contactNo,occupation,occupationAddress,salary,birthDate,birthPlace,workYears,civilStatus,gender,age,cmName,cmAge,cmAddress,cmContactNo,cmOccupation,cmOccupatioAdd,cmSalary,cm_Name,cm_Age,cm_Address,cm_ContactNo,cm_Occupation,cm_OccupationAdd,cm_Salary) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8,#d9,#d10,#d11,#d12,#d13,#d14,#d15,#d16,#d17,#d18,#d19,#d20,#d21,#d22,#d23,#d24,#25,#26)";
SqlCommand cmd = new SqlCommand(sSQL, cn);
//new client
;
SqlParameter name = new SqlParameter("#d1", SqlDbType.Char, 10);
name.Value = textBox1.Text.ToString();
cmd.Parameters.Add(name);
SqlParameter address = new SqlParameter("#d2", SqlDbType.VarChar, 50);
address.Value = textBox2.Text.ToString();
cmd.Parameters.Add(address);
SqlParameter contactNo = new SqlParameter("#d3", SqlDbType.Char, 10);
contactNo.Value = textBox3.Text.ToString();
cmd.Parameters.Add(contactNo);
SqlParameter occupation = new SqlParameter("#d4", SqlDbType.Char, 50);
occupation.Value = textBox4.Text.ToString();
cmd.Parameters.Add(occupation);
SqlParameter occupationAddress = new SqlParameter("#d5", SqlDbType.VarChar, 50);
occupationAddress.Value = textBox5.Text.ToString();
cmd.Parameters.Add(occupationAddress);
SqlParameter salary = new SqlParameter("#d6", SqlDbType.Char, 10);
salary.Value = textBox6.Text.ToString();
cmd.Parameters.Add(salary);
SqlParameter birthDate = new SqlParameter("#d7", SqlDbType.VarChar, 10);
birthDate.Value = maskedTextBox1.Text.ToString();
cmd.Parameters.Add(birthDate);
SqlParameter birthPlace = new SqlParameter("#d8", SqlDbType.Char, 50);
birthPlace.Value = textBox8.Text.ToString();
cmd.Parameters.Add(birthPlace);
SqlParameter workYears = new SqlParameter("#d9", SqlDbType.Char, 2);
workYears.Value = textBox9.Text.ToString();
cmd.Parameters.Add(workYears);
SqlParameter civilStatus = new SqlParameter("#d10", SqlDbType.Char, 10);
civilStatus.Value = comboBox1.Text.ToString();
cmd.Parameters.Add(civilStatus);
SqlParameter gender = new SqlParameter("#d11", SqlDbType.Char, 10);
gender.Value = comboBox2.Text.ToString();
cmd.Parameters.Add(gender);
SqlParameter age = new SqlParameter("#d12", SqlDbType.Char, 2);
age.Value = textBox12.Text.ToString();
cmd.Parameters.Add(age);
//co-maker 1
SqlParameter cmName = new SqlParameter("#d13", SqlDbType.Char, 2);
cmName.Value = textBox13.Text.ToString();
cmd.Parameters.Add(cmName);
SqlParameter cmAge = new SqlParameter("#d14", SqlDbType.VarChar, 50);
cmAge.Value = textBox14.Text.ToString();
cmd.Parameters.Add(cmAge);
SqlParameter cmAddress = new SqlParameter("#d15", SqlDbType.VarChar, 50);
cmAddress.Value = textBox15.Text.ToString();
cmd.Parameters.Add(cmAddress);
SqlParameter cmContactNo = new SqlParameter("#d16", SqlDbType.VarChar, 10);
cmContactNo.Value = textBox16.Text.ToString();
cmd.Parameters.Add(cmContactNo);
SqlParameter cmOccupation = new SqlParameter("#d17", SqlDbType.Char, 20);
cmOccupation.Value = textBox17.Text.ToString();
cmd.Parameters.Add(cmOccupation);
SqlParameter cmOccupatioAdd = new SqlParameter("#d18", SqlDbType.VarChar, 50);
cmOccupatioAdd.Value = textBox18.Text.ToString();
cmd.Parameters.Add(cmOccupatioAdd);
SqlParameter cmSalary = new SqlParameter("#d19", SqlDbType.VarChar, 10);
cmSalary.Value = textBox19.Text.ToString();
cmd.Parameters.Add(cmSalary);
//co-maker 2
SqlParameter cm_Name = new SqlParameter("#d20", SqlDbType.Char, 10);
cm_Name.Value = textBox26.Text.ToString();
cmd.Parameters.Add(cm_Name);
SqlParameter cm_Age = new SqlParameter("#d21", SqlDbType.VarChar, 10);
cm_Age.Value = textBox25.Text.ToString();
cmd.Parameters.Add(cm_Age);
SqlParameter cm_Address = new SqlParameter("#d22", SqlDbType.VarChar, 50);
cm_Address.Value = textBox23.Text.ToString();
cmd.Parameters.Add(cm_Address);
SqlParameter cm_ContactNo = new SqlParameter("#d23", SqlDbType.VarChar, 20);
cm_ContactNo.Value = textBox24.Text.ToString();
cmd.Parameters.Add(cm_ContactNo);
SqlParameter cm_Occupation = new SqlParameter("#d24", SqlDbType.VarChar, 50);
cm_Occupation.Value = textBox22.Text.ToString();
cmd.Parameters.Add(cm_Occupation);
SqlParameter cm_OccupationAdd = new SqlParameter("#d25", SqlDbType.VarChar, 50);
cm_OccupationAdd.Value = textBox21.Text.ToString();
cmd.Parameters.AddWithValue("#25", textBox21.Text);
//cmd.Parameters.Add(cm_OccupationAdd);
SqlParameter cm_Salary = new SqlParameter("#d26", SqlDbType.VarChar, 2);
cm_Salary.Value = textBox20.Text.ToString();
cmd.Parameters.AddWithValue("#26", textBox20.Text);
//cmd.Parameters.Add(cm_Salary);
int temp = 0;
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
cn.Close();
MessageBox.Show("New client added Successfully!");
}
else
{
MessageBox.Show("data not added!");
return;
}
}
else
{`enter code here`
MessageBox.Show("Name of two Co-Maker are the same", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Data Error");
return;
}
}
and here my second windows form
private void button1_Click(object sender, EventArgs e)
{
if (RequiredEntry() == true)
{
return;
}
try
{
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-79MM8LM;Initial Catalog=lend;Integrated Security=True");
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
cn.Open();
//if (textBox13.Text.Trim() != textBox26.Text.Trim())
if (String.IsNullOrEmpty(comboBox1.Text))
{
string sSQL = "insert into costumerinfo(name, amount, interest, daysOfPayment, payPerDay, totalAmount, processingFee, insurance, notarial) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8)";
SqlCommand cmd = new SqlCommand(sSQL, cn);
//new client
//SqlParameter clientID = new SqlParameter("#d1", SqlDbType.Char, 10);
//clientID.Value = textBox1.Text.ToString();
//cmd.Parameters.Add(clientID);
SqlParameter name = new SqlParameter("#d1", SqlDbType.Char, 10);
name.Value = comboBox1.Text.ToString();
cmd.Parameters.Add(name);
SqlParameter amount = new SqlParameter("#d2", SqlDbType.VarChar, 50);
amount.Value = textBox2.Text.ToString();
cmd.Parameters.Add(amount);
SqlParameter interest = new SqlParameter("#d3", SqlDbType.Char, 10);
interest.Value = textBox3.Text.ToString();
cmd.Parameters.Add(interest);
SqlParameter daysOfPayment = new SqlParameter("#d4", SqlDbType.Char, 50);
daysOfPayment.Value = textBox4.Text.ToString();
cmd.Parameters.Add(daysOfPayment);
SqlParameter payPerDay = new SqlParameter("#d5", SqlDbType.VarChar, 50);
payPerDay.Value = label10.Text.ToString();
cmd.Parameters.Add(payPerDay);
SqlParameter totalAmount = new SqlParameter("#d6", SqlDbType.VarChar, 50);
totalAmount.Value = label11.Text.ToString();
cmd.Parameters.Add(totalAmount);
SqlParameter processingFee = new SqlParameter("#d7", SqlDbType.Char, 10);
processingFee.Value = textBox7.Text.ToString();
cmd.Parameters.Add(processingFee);
SqlParameter insurance = new SqlParameter("#d8", SqlDbType.VarChar, 10);
insurance.Value = textBox8.Text.ToString();
cmd.Parameters.Add(insurance);
SqlParameter notarial = new SqlParameter("#d9", SqlDbType.Char, 50);
notarial.Value = textBox9.Text.ToString();
cmd.Parameters.Add(notarial);
int temp = 0;
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
cn.Close();
MessageBox.Show("New transaction added Successfully!");
}
else
{
MessageBox.Show("data not added!");
return;
}
}
else
{
MessageBox.Show("Name of two Co-Maker are the same", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Data Error");
return;
}
}
but here I got in my database
[the new data was adding but create new line][1]
[i want to add data align with name][2]
[1]: https://i.stack.imgur.com/B6Gb2.png
[2]: https://i.stack.imgur.com/QaLov.png
can you help me thanks
What you want, is to insert from one and update from the other.
SQL insert command -> The INSERT INTO statement is used to insert new records in a table.
SQL update command -> The UPDATE statement is used to modify the existing records in a table.
So your algorithm should be something like this:
Select from the table to see if the row exists
select * from costumerinfo where name = #name
If it does not exist, then insert
insert into costumerinfo
If it does exist, update the relevant values
update customerinfo set ... where name = #name
You can of course change the second form and directly call
string sSQL = "update costumerinfo set amount=#d1, interest=#d2, daysOfPayment = #d3, payPerDay = #d4, totalAmount= $d5, processingFee=#d6, insurance #d7, notarial #d8) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8) where name = name=#d9";

how to solve that error "Conversion failed when converting date and/or time from character string"

I am creating a new application and I am trying to insert a DateTime data type into SQLServer. the error says
Conversion failed when converting date and/or time from character string.
Code:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (#StaffID, #Cash, #AmountPaid,
#type, #PaymentDate, #StaffID)";
cmd = new SqlCommand(Insertcmd, con);
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("#PatientID", SqlDbType.Int);
param[0].Value = PatientID;
param[1] = new SqlParameter("#Cash", SqlDbType.Float);
param[1].Value = Cash;
param[2] = new SqlParameter("#AmountPaid", SqlDbType.Float);
param[2].Value = AmountPaid;
param[3] = new SqlParameter("#type", SqlDbType.NVarChar, 255);
param[3].Value = type;
param[4] = new SqlParameter("#PaymentDate", SqlDbType.DateTime);
param[4].Value = Convert.ToDateTime( DateTime.Now.ToString("yyyy-
MM-dd 00:00:00")); // Error
param[5] = new SqlParameter("#StaffID", SqlDbType.Int, 255);
param[5].Value = StaffID;
//Open the connection to database
con.Open();
try
{
if (con.State == System.Data.ConnectionState.Open)
{
//Execute the Adding process
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
}catch{}
Just use
param[4].Value = DateTime.Now;
Instead of
param[4].Value = Convert.ToDateTime( DateTime.Now.ToString("yyyy-
MM-dd 00:00:00"));
If you need to remove the time part then use:
param[4].Value = DateTime.Now.Date;
Or as #DBro mentioned in the comments
param[4].Value = DateTime.Today;
Update 1
If you are having problem passing the date parameter try using the following sql command without passing the PaymentDate parameter:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (#StaffID, #Cash, #AmountPaid,
#type, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), #StaffID)";
The whole code will be:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (#StaffID, #Cash, #AmountPaid,
#type, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), #StaffID)";
cmd = new SqlCommand(Insertcmd, con);
SqlParameter[] param = new SqlParameter[5];
param[0] = new SqlParameter("#PatientID", SqlDbType.Int);
param[0].Value = PatientID;
param[1] = new SqlParameter("#Cash", SqlDbType.Float);
param[1].Value = Cash;
param[2] = new SqlParameter("#AmountPaid", SqlDbType.Float);
param[2].Value = AmountPaid;
param[3] = new SqlParameter("#type", SqlDbType.NVarChar, 255);
param[3].Value = type;
param[4] = new SqlParameter("#StaffID", SqlDbType.Int, 255);
param[4].Value = StaffID;
//Open the connection to database
con.Open();
try
{
if (con.State == System.Data.ConnectionState.Open)
{
//Execute the Adding process
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
}catch{}
Reference
Best approach to remove time part of datetime in SQL Server
Update 2
You must reorder the parameters in the SQL command since you are inserting thr #type parameter in the PaymentDate column.

(C# application with oracle database) returning out parameters in stored procedures

I am new to Oracle. I am receiving an exception when I am trying to get the values of the out parameters in the following procedure:
The procedure's job is to bring some information about a drug, given its ID, and store results in out parameters
create or replace
PROCEDURE RETREIVE_DRUG(
drugId in "Drug"."DRUG_ID"%type,
drugName OUT "Drug"."NAME"%type,
prodDate OUT "Drug"."PRODUCTION_DATE"%type,
expireDate OUT "Drug"."EXPIRATION_DATE"%type,
price OUT "Drug"."PRICE"%type,
description OUT "Drug"."DESCRIPTION"%type,
quantity OUT "Drug"."QUANTITY"%type,
buying OUT "Drug"."COST"%type,
company OUT "Drug"."COMPANY"%type
)
AS
BEGIN
SELECT "NAME", "PRODUCTION_DATE", "EXPIRATION_DATE", "PRICE", "DESCRIPTION", "QUANTITY", "COST", "COMPANY"
INTO drugName, prodDate, expireDate, price, description, quantity, buying, company
FROM "Drug"
WHERE "Drug"."DRUG_ID" = drugId;
END RETREIVE_DRUG;
the c# code that invokes the procedure is as follows
public String[] Get_Drug(int id)
{
OpenConnection();
OracleCommand oraCmd = new OracleCommand();
oraCmd.Connection = con;
oraCmd.CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = "RETREIVE_DRUG";
OracleParameter[] param = new OracleParameter[9];
param[0] = new OracleParameter("DRUG_ID", OracleDbType.Decimal);
param[0].Value = id;
param[1] = new OracleParameter("NAME", OracleDbType.Varchar2);
param[1].Direction = ParameterDirection.Output;
param[2] = new OracleParameter("PRODUCTION_DATE", OracleDbType.Date);
param[2].Direction = ParameterDirection.Output;
param[3] = new OracleParameter("EXPIRATION_DATE", OracleDbType.Date);
param[3].Direction = ParameterDirection.Output;
param[4] = new OracleParameter("PRICE", OracleDbType.Decimal);
param[4].Direction = ParameterDirection.Output;
param[5] = new OracleParameter("DESCRIPTION", OracleDbType.Varchar2);
param[5].Direction = ParameterDirection.Output;
param[6] = new OracleParameter("QUANTITY", OracleDbType.Decimal);
param[6].Direction = ParameterDirection.Output;
param[7] = new OracleParameter("COST", OracleDbType.Decimal);
param[7].Direction = ParameterDirection.Output;
param[8] = new OracleParameter("COMPANY", OracleDbType.Varchar2);
param[8].Direction = ParameterDirection.Output;
oraCmd.Parameters.AddRange(param);
oraCmd.ExecuteNonQuery();
CloseConnection();
String[] ret = new String[8];
ret[0] =oraCmd.Parameters["NAME"].Value.ToString();
ret[1] =oraCmd.Parameters["PRODUCTION_DATE"].Value.ToString();
ret[2] =oraCmd.Parameters["EXPIRATION_DATE"].Value.ToString();
ret[3] =oraCmd.Parameters["PRICE"].Value.ToString();
ret[4] =oraCmd.Parameters["DESCRIPTION"].Value.ToString();
ret[5] =oraCmd.Parameters["QUANTITY"].Value.ToString();
ret[6] =oraCmd.Parameters["COST"].Value.ToString();
ret[7] =oraCmd.Parameters["COMPANY"].Value.ToString();
return ret;
}
But when I run the code, the following exception is shown up:
PL\SQL: numeric or value error
Although I am sure about the names and the types. Please help. I have done a lot of effort in the problem without being able to solve it!
I defined the size of varchar parameters (drugName, description, company) and changed parameter names exactly as they are in Oracle code, for instance, buying instead of COST. Finally added binding by name and below function worked fine:
public String[] Get_Drug(int id)
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=XE";
con.Open();
OracleCommand oraCmd = new OracleCommand();
oraCmd.Connection = con;
oraCmd.BindByName = true;
oraCmd.CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = "RETREIVE_DRUG";
OracleParameter[] param = new OracleParameter[9];
param[0] = new OracleParameter("drugId", OracleDbType.Decimal);
param[0].Direction = ParameterDirection.Input;
param[0].Value = id;
param[1] = new OracleParameter("drugName", OracleDbType.Varchar2);
param[1].Direction = ParameterDirection.Output;
param[1].Size = 30;
param[2] = new OracleParameter("prodDate", OracleDbType.Date);
param[2].Direction = ParameterDirection.Output;
param[3] = new OracleParameter("expireDate", OracleDbType.Date);
param[3].Direction = ParameterDirection.Output;
param[4] = new OracleParameter("price", OracleDbType.Decimal);
param[4].Direction = ParameterDirection.Output;
param[5] = new OracleParameter("description", OracleDbType.Varchar2);
param[5].Size = 30;
param[5].Direction = ParameterDirection.Output;
param[6] = new OracleParameter("quantity", OracleDbType.Decimal);
param[6].Direction = ParameterDirection.Output;
param[7] = new OracleParameter("buying", OracleDbType.Decimal);
param[7].Direction = ParameterDirection.Output;
param[8] = new OracleParameter("company", OracleDbType.Varchar2);
param[8].Size = 30;
param[8].Direction = ParameterDirection.Output;
oraCmd.Parameters.AddRange(param);
oraCmd.ExecuteNonQuery();
con.Close();
String[] ret = new String[8];
ret[0] = oraCmd.Parameters["drugName"].Value.ToString();
ret[1] = oraCmd.Parameters["prodDate"].Value.ToString();
ret[2] = oraCmd.Parameters["expireDate"].Value.ToString();
ret[3] = oraCmd.Parameters["price"].Value.ToString();
ret[4] = oraCmd.Parameters["description"].Value.ToString();
ret[5] = oraCmd.Parameters["quantity"].Value.ToString();
ret[6] = oraCmd.Parameters["buying"].Value.ToString();
ret[7] = oraCmd.Parameters["company"].Value.ToString();
return ret;
}
Probably second and third step is not key if you bind parameters by position, but defining by name is more readable. Here is the table structure and example data I used for test purposes:
create table "Drug" ("DRUG_ID" number, "NAME" varchar2(10), "PRODUCTION_DATE" date,
"EXPIRATION_DATE" date, "PRICE" number, "DESCRIPTION" varchar2(10), "QUANTITY" number,
"COST" number, "COMPANY" varchar2(10));
insert into "Drug" values (
1, 'Name1', date '2015-01-18', date '2016-01-18', 100, 'Desc1', 900, 30, 'Comp1');

Data insertion to the database is not happening using asp.net wih c#

This is my aspx.cs page,these codes should insert the values into the database,but presently its not going good,its not inserting into database,i am not getting any errors but insertion is not happening,i have no idea what is going wrong.IS there an possibility of SqlException? or any other issues?
protected void btnSkipSubmit_Click(object sender, EventArgs e)
{
int random = 0;
bool isValidInt = int.TryParse(txtrandom.Text, out random);
//string dummmy = "D";
//int dum = 0;
Patient p = new Patient();
//PatientBill pb = new PatientBill();
myConnection obj1 = new myConnection();
DateTime sdt = DateTime.Now;
// string a;
string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
string cmdString = "";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlTransaction transaction;
if (isValidInt)
{
for (int i = 0; i < random; i++)
{
//a = obj1.fnSkipPatient(p);
string dummmy = "D";
int dum = 0;
//DateTime sdt = DateTime.Now;
cmdString = "INSERT INTO Patient_Data(PatientID,PatientName,F_H_G,F_H_GName,AgeOnRegn,Email,ContactNo,Gender,Married,AddressLine1,AddressLine2,City,PinCode,Religion,Occupation,RegTime,VisitDate,CurrDept,NextDept,PayID,PayDet1,PayDet2,PayDet3,PayValidity,Archived,UpdateUser,UpdateShift,UpdateDate,LocID,AddressLine3,Remark) VALUES (#PatientID,#PatientName,#F_H_G,#F_H_GName,#AgeOnRegn,#Email,#ContactNo,#Gender,#Married,#AddrLine1,#AddrLine2,#City,#PinCode,#Religion,#Occupation,#RegTime,#VisitDate,#CurrDept,#NextDept,#PayID,#PayDet1,#PayDet2,#PayDet3,#PayValidity,#Archived,#UpdateUser,#UpdateShift,#UpdateDate,#LocID,#AddrLine3,#Remark)";
con = new SqlConnection(str);
try
{
//log.Debug("Entering fnAddPatient method-Function to add a new patient into the database,generate registration bill");
con.Open();
transaction = con.BeginTransaction();
cmd = new SqlCommand(cmdString, con, transaction);
cmd.Parameters.Add("#PatientID", SqlDbType.VarChar, 12);
cmd.Parameters["#PatientID"].Value = p.HospitalNo;
cmd.Parameters.Add("#PatientName", SqlDbType.VarChar, 30);
cmd.Parameters["#PatientName"].Value = dummmy;
cmd.Parameters.Add("#F_H_G", SqlDbType.VarChar, 1);
cmd.Parameters["#F_H_G"].Value = dummmy;
cmd.Parameters.Add("#F_H_GName", SqlDbType.VarChar, 30);
cmd.Parameters["#F_H_GName"].Value = dummmy;
cmd.Parameters.Add("#AgeOnRegn", SqlDbType.Int);
cmd.Parameters["#AgeOnRegn"].Value = dum;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 40);
cmd.Parameters["#Email"].Value = dummmy;
cmd.Parameters.Add("#ContactNo", SqlDbType.VarChar, 12);
cmd.Parameters["#ContactNo"].Value = dummmy;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 1);
cmd.Parameters["#Gender"].Value = dummmy;
cmd.Parameters.Add("#Married", SqlDbType.VarChar, 1);
cmd.Parameters["#Married"].Value = dummmy;
cmd.Parameters.Add("#AddrLine1", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine1"].Value = dummmy;
cmd.Parameters.Add("#AddrLine2", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine2"].Value = dummmy;
cmd.Parameters.Add("#AddrLine3", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine3"].Value = dummmy;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 20);
cmd.Parameters["#City"].Value = dummmy;
cmd.Parameters.Add("#PinCode", SqlDbType.Int);
cmd.Parameters["#PinCode"].Value = dum;
cmd.Parameters.Add("#Religion", SqlDbType.VarChar, 20);
cmd.Parameters["#Religion"].Value = dummmy;
cmd.Parameters.Add("#Occupation", SqlDbType.VarChar, 20);
cmd.Parameters["#Occupation"].Value = dummmy;
cmd.Parameters.Add("#RegTime", SqlDbType.DateTime);
cmd.Parameters["#RegTime"].Value = sdt;
cmd.Parameters.Add("#VisitDate", SqlDbType.DateTime);
cmd.Parameters["#VisitDate"].Value = sdt;
cmd.Parameters.Add("#CurrDept", SqlDbType.Int);
cmd.Parameters["#CurrDept"].Value = dum;
cmd.Parameters.Add("#NextDept", SqlDbType.Int);
cmd.Parameters["#NextDept"].Value = dum;
cmd.Parameters.Add("#PayId", SqlDbType.VarChar, 2);
cmd.Parameters["#PayId"].Value = dummmy;
cmd.Parameters.Add("#PayDet1", SqlDbType.VarChar, 15);
cmd.Parameters["#PayDet1"].Value = dummmy;
cmd.Parameters.Add("#PayDet2", SqlDbType.VarChar, 50);
cmd.Parameters["#PayDet2"].Value = dummmy;
cmd.Parameters.Add("#PayDet3", SqlDbType.VarChar, 15);
cmd.Parameters["#PayDet3"].Value = dummmy;
cmd.Parameters.Add("#PayValidity", SqlDbType.DateTime);
cmd.Parameters["#PayValidity"].Value = sdt;
cmd.Parameters.Add("#Archived", SqlDbType.VarChar, 1);
cmd.Parameters["#Archived"].Value = dummmy;
cmd.Parameters.Add("#UpdateUser", SqlDbType.VarChar, 20);
cmd.Parameters["#UpdateUser"].Value = dummmy;
cmd.Parameters.Add("#UpdateShift", SqlDbType.Int);
cmd.Parameters["#UpdateShift"].Value = dum;
cmd.Parameters.Add("#UpdateDate", SqlDbType.DateTime);
cmd.Parameters["#UpdateDate"].Value = sdt;
cmd.Parameters.Add("#PatientCount", SqlDbType.Int);
cmd.Parameters["#PatientCount"].Value = dum;
cmd.Parameters.Add("#LocId", SqlDbType.VarChar, 2);
cmd.Parameters["#LocId"].Value = dummmy;
cmd.Parameters.Add("#Remark", SqlDbType.VarChar, 100);
cmd.Parameters["#Remark"].Value = dummmy;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
string result = cmd.ExecuteNonQuery().ToString();
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
}
}
}
Move cmd.Parameters.Clear(); after cmd.ExecuteNonQuery()
Try with cmd.ExecuteNonQuery() only.
Also note that if your isValidInt is false, your query will not be executed.. So, first check whether your isValidInt is true. Better you change your logic
You must commit changes in transaction and also cosider transaction.Rollback(); in the catch
I think you are missing transaction.Commit(); after cmd.ExecuteNonQuery();.
try
{
con.Open();
transaction = con.BeginTransaction();
cmd = new SqlCommand(cmdString, con, transaction);
cmd.Parameters.AddWithValue("#PatientID", p.HospitalNo);
// Continue your usual work
cmd.Parameters.AddWithValue("#Remark", dummmy);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
transaction.Commit();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
transaction.Rollback();
}
finally
{
con.Close();
}
Something similar to above code should work for you.
Hope it helps.
execute the following code in server management studio....
GRANT INSERT ON [dbo].[Patient_Data] TO public
hope it works...
1)Make Sure that the connection string is valid.
2)If you close and open the sql server management studio the database will be switched over to "master", you have to change the control to your DB.You can see a dropdownbox in the sql editor tool bar where you can select the DB that where the current query should executed.

Export data from CSV to sql server using asp.net C# TextFieldParser

I am working on exporting CSV to SQL server but it doesn't export anything. I have following code:
protected void uploadButton_Click(object sender, EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("IP");
tblReadCSV.Columns.Add("activityStart");
tblReadCSV.Columns.Add("activityEnd");
tblReadCSV.Columns.Add("RCPTcommands");
tblReadCSV.Columns.Add("DataCommands");
tblReadCSV.Columns.Add("MessageRecipients");
tblReadCSV.Columns.Add("FilterResultColor");
tblReadCSV.Columns.Add("complaintRate");
tblReadCSV.Columns.Add("trapStart");
tblReadCSV.Columns.Add("trapEnd");
tblReadCSV.Columns.Add("trapHits");
tblReadCSV.Columns.Add("sampleHelo");
tblReadCSV.Columns.Add("sampleMailFrom");
tblReadCSV.Columns.Add("comments");
tblReadCSV.Columns.Add("URL");
string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadFiles/" + path));
path = Server.MapPath("~/UploadFiles/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
string strCon = ConfigurationManager.ConnectionStrings["conMailMonitor"].ConnectionString;
string strSql = "INSERT INTO tblSnds(IP,activityStart,activityEnd,RCPTcommands,DataCommands,MessageRecipients,FilterResultColor,complaintRate,trapStart,trapEnd,trapHits,sampleHelo,sampleMailFrom,comments,URL)VALUES(#IP,#activityStart,#activityEnd,#RCPTcommands,#DataCommands,#MessageRecipients,#FilterResultColor,#complaintRate,#trapStart,#trapEnd,#trapHits,#sampleHelo,#sampleMailFrom,#comments,#URL)";
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#IP", SqlDbType.VarChar, 50, "IP");
cmd.Parameters.Add("#activityStart", SqlDbType.VarChar, 50, "activityStart");
cmd.Parameters.Add("#activityEnd", SqlDbType.VarChar, 50, "activityEnd");
cmd.Parameters.Add("#RCPTcommands", SqlDbType.VarChar, 50, "RCPTcommands");
cmd.Parameters.Add("#DataCommands", SqlDbType.VarChar, 50, "DataCommands");
cmd.Parameters.Add("#MessageRecipients", SqlDbType.VarChar, 50, "MessageRecipients");
cmd.Parameters.Add("#FilterResultColor", SqlDbType.VarChar, 50, "FilterResultColor");
cmd.Parameters.Add("#complaintRate", SqlDbType.VarChar, 50, "complaintRate");
cmd.Parameters.Add("#trapStart", SqlDbType.VarChar, 50, "trapStart");
cmd.Parameters.Add("#trapEnd", SqlDbType.VarChar, 50, "trapEnd");
cmd.Parameters.Add("#trapHits", SqlDbType.VarChar, 50, "trapHits");
cmd.Parameters.Add("#sampleHelo", SqlDbType.VarChar, 50, "activityEnd");
cmd.Parameters.Add("#sampleMailFrom", SqlDbType.VarChar, 50, "sampleMailFrom");
cmd.Parameters.Add("#comments", SqlDbType.VarChar, 50, "comments");
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 50, "URL");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
Label1.Text = "File successfully uploaded";
}
Contents of CSV are:
216.211.128.7,8/12/2013 8:00 AM,8/13/2013 8:00 AM,6610,5642,5644,GREEN,< 0.1%,8/12/2013 11:23 AM,8/12/2013 11:36 AM,4,mail2.adhost.com,bpsupport#betterphoto.com,
When I debug, I see that control doesnt go inside the while loop
while (!(csvParser.EndOfData == true))
Please suggest how to do it ?
You have to use MyReader.ReadFields() to advance the reader to the next line:
// csvParser.ReadLine(); <-- remove this
while (!csvParser.EndOfData) {
string[] fields = csvParser.ReadFields();
tblReadCSV.Rows.Add(fields);
}
MSDN:
Reads all fields on the current line, returns them as an array of
strings, and advances the cursor to the next line containing data.
The problem was that you are using ReadLine first which skips the first line.

Categories

Resources