Excel to DataTable Insert - c#

I am trying to insert into a database from Excel, and I've got all values from Excel. When I insert into my database I get Factal Exception. How do I recover from this exception?
MySqlCommand commd = new MySqlCommand();
commd.Connection = OpenConnection();
commd.CommandText = "INSERT INTO sqa_tracking(IID,STARTDATE,ENDDATE,WEEK,SUPPLIER,LINENO,ORDER_ID,BRCARID,PAGE_FIRST,PAGE_LAST,PAGE_COUNT,ARTICLE_NO,COUNT_LINENO,TOTAL_NR_OF_ITEMS,CAR_SUPPLIER,CONTENT_PROVIDER_NAME,MANIFESTATION,FACTOR,UNITS,DATE_OF_SUBMISSION,UNITS_KEY,COUNT_UNITS_KEY,TOTAL_NR_OF_UNITS,ERRORS,KPI_ERRORS,OBII_ELEMENT,CAR_FIELD_NAME,ERROR_TYPE,WRONG_CAPTURE_IN_FILE,CORRECT_CAPTURE_WOULD_BE,REPEATING_IN_CAR,SOURCE_FILE_TYPE,FULL_AUTOM_CONV,ERROR_IN_SOURCE_FILE,ROOT_CAUSE_OF_THE_ERROR,PREVENTIVE_MEASURES,DATE_OF_IMPLEMENTATION,DATE_OF_TRANSMISSION,VALIDATED) VALUES (#IID,#STARTDATE,#ENDDATE,#WEEK,#SUPPLIER,#LINENO,#ORDER_ID,#BRCARID,#PAGE_FIRST,#PAGE_LAST,#PAGE_COUNT,#ARTICLE_NO,#COUNT_LINENO,#TOTAL_NR_OF_ITEMS,#CAR_SUPPLIER,#CONTENT_PROVIDER_NAME,#MANIFESTATION,#FACTOR,#UNITS,#DATE_OF_SUBMISSION,#UNITS_KEY,#COUNT_UNITS_KEY,#TOTAL_NR_OF_UNITS,#ERRORS,#KPI_ERRORS,#OBII_ELEMENT,#CAR_FIELD_NAME,#ERROR_TYPE,#WRONG_CAPTURE_IN_FILE,#CORRECT_CAPTURE_WOULD_BE,#REPEATING_IN_CAR,#SOURCE_FILE_TYPE,#FULL_AUTOM_CONV,#ERROR_IN_SOURCE_FILE,#ROOT_CAUSE_OF_THE_ERROR,#PREVENTIVE_MEASURES,#DATE_OF_IMPLEMENTATION,#DATE_OF_SUBMISSION,#VALIDATED) ";
commd.Parameters.AddWithValue("#STARTDATE", StartDate);
commd.Parameters.AddWithValue("#ENDDATE", EndDate);
commd.Parameters.AddWithValue("#WEEK", Week);
commd.Parameters.AddWithValue("#SUPPLIER", Supplier);
commd.Parameters.AddWithValue("#LINENO", LineNo);
commd.Parameters.AddWithValue("#ORDER_ID", ORDERID);
commd.Parameters.AddWithValue("#BRCARID", "");
commd.Parameters.AddWithValue("#PAGE_FIRST", PageFirst);
commd.Parameters.AddWithValue("#PAGE_LAST", Pagelast);
commd.Parameters.AddWithValue("#PAGE_COUNT", Pagecount);
commd.Parameters.AddWithValue("#ARTICLE_NO", ArticleNo);
commd.Parameters.AddWithValue("#COUNT_LINENO", COUNTLineNo);
commd.Parameters.AddWithValue("#TOTAL_NR_OF_ITEMS", Totalnrofitems);
commd.Parameters.AddWithValue("#CAR_SUPPLIER", CARSupplier);
commd.Parameters.AddWithValue("#CONTENT_PROVIDER_NAME", ContentProvidename);
commd.Parameters.AddWithValue("#MANIFESTATION", Manifestation);
commd.Parameters.AddWithValue("#FACTOR", AU);
commd.Parameters.AddWithValue("#UNITS", Units);
commd.Parameters.AddWithValue("#DATE_OF_SUBMISSION", Dateoftransmission);
commd.Parameters.AddWithValue("#UNITS_KEY", unitskey);
commd.Parameters.AddWithValue("#COUNT_UNITS_KEY", COUNTunitskey);
commd.Parameters.AddWithValue("ERRORS", Errors);
commd.Parameters.AddWithValue("#KPI_ERRORS", KPIErrors);
commd.Parameters.AddWithValue("#OBII_ELEMENT", OBIIElement);
commd.Parameters.AddWithValue("#CAR_FIELD_NAME", CARFieldname);
commd.Parameters.AddWithValue("#ERROR_TYPE", Errortype);
commd.Parameters.AddWithValue("#IID", IID);
commd.Parameters.AddWithValue("#WRONG_CAPTURE_IN_FILE", Wrongcaptureinfile);
commd.Parameters.AddWithValue("#CORRECT_CAPTURE_WOULD_BE", Correctcapturewouldbe);
commd.Parameters.AddWithValue("#REPEATING_IN_CAR", RepeatinginCAR);
commd.Parameters.AddWithValue("#SOURCE_FILE_TYPE", Sourcefiletype);
commd.Parameters.AddWithValue("#FULL_AUTOM_CONV", FulAutomConv);
commd.Parameters.AddWithValue("#ERROR_IN_SOURCE_FILE", Errorinsourcefile);
commd.Parameters.AddWithValue("#ROOT_CAUSE_OF_THE_ERROR", RootCauseoftheError);
commd.Parameters.AddWithValue("#PREVENTIVE_MEASURES", PreventiveMeasures);
commd.Parameters.AddWithValue("#DATE_OF_IMPLEMENTATION", DateofImplementation);
commd.Parameters.AddWithValue("#VALIDATED", Validated);
commd.ExecuteNonQuery();`
I used inline query and I got the parameter values from DataTable.

Always remember that fatal error occurred during command execution only because of incorrect parameters value name.
so correct the parameter value to avoid fetal errors during command execution
You have not provided parameter value for TOTAL_NR_OF_UNITS & DATE_OF_TRANSMISSION.
Also Please follow the order in your insert query and while adding parameters, makes it easier to troubleshoot.
commd.Parameters.AddWithValue("#TOTAL_NR_OF_UNITS",TotalNrOfUnits);
commd.Parameters.AddWithValue("#DATE_OF_TRANSMISSION", DateOfTransmission);

Either this . . .
SqlCommand cmd = new SqlCommand("insert into tbl_insert values (#id,#name,#Email,#City)");
cmd.Parameters.AddWithValue("#id", Convert.ToInt32(txtId.Text));
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#City", txtboxCity.Text);
...or this...
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();
...should work fine.

Related

AddWithValue in asp.net C# Web app for Oracle Database

i used Addwithvalue attribute to include values in sql command query string; it was working well in MSSQL but i dont know its is working for Oracle DB , it gives error CS1061
i tried to import using System.Data.OracleClient; which isn't supported. can anyone confirm addwithvalue exist in oracle 11g enterprise edition?
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO member_master_tbl( full_name,dob,contact_no,email, state, city,pincode, full_address, member_id, password,account_status) values (#full_name,#dob,#contact_no,#email, #state, #city,#pincode, #full_address, #member_id, #password,#account_status)";
cmd.Parameters.AddWithValue("#full_name", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#contact_no", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox6.Text.Trim());
cmd.Parameters.AddWithValue("#state", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#city", TextBox7.Text.Trim());
cmd.Parameters.AddWithValue("#pincode", TextBox8.Text.Trim());
cmd.Parameters.AddWithValue("#full_address", TextBox9.Text.Trim());
cmd.Parameters.AddWithValue("#member_id", TextBox10.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox11.Text.Trim());
cmd.Parameters.AddWithValue("#account_status", "pending");
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful , Kindly go to login page for login.')</script>");

Combining Two SQL Queries - ASP.NET

I have two SQL queries:
SqlCommand cmdone = new SqlCommand("update HardwareDetails Set Transstat = #Transstat where AssetNo = #AssetNo", con);
cmdone.Parameters.AddWithValue(#"Transstat", "Raised");
cmdone.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmdone.ExecuteNonQuery();
cmdone.Dispose();
And:
SqlCommand cmd = new SqlCommand("Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (#FrmName,#FrmEmpId,#ToName", con);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
Is there a way to combine them into a single query?
Put a semi-colon between the two SQL statements, and add all the parameters.
using (SqlCommand cmd = new SqlCommand("UPDATE HardwareDetails SET Transstat = #Transstat WHERE AssetNo = AssetNo; INSERT INTO TransferRequest (FrmName, FrmEmpId, ToName) VALUES (#FrmName, #FrmEmpId, #ToName)", con))
{
cmd.Parameters.AddWithValue(#"Transstat", "Raised");
cmd.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
}
Comments:
Its best practice (because its safer) to create your cmd within a using block.
AddWithValue should not be used, instead create the SqlParameter using its constructor and specify the type and precision. E.g. cmd.Parameters.Add(new SqlParameter("#Transstat", SqlDataType.VarChar, 6) { Value = "Raised"});
As pointed out by Liam as it stands this does break the Single Responsibility Principle. Personally I would only use this method if the two statements are linked/related in some way.
string query = #"
update HardwareDetails Set Transstat = #Transstat where AssetNo = #AssetNo
Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (#FrmName,#FrmEmpId,#ToName)";
SqlCommand cmd= new SqlCommand(query,con);
cmd.Parameters.AddWithValue(#"Transstat", "Raised");
cmd.Parameters.AddWithValue(#"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(#"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(#"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(#"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();

INSERT INTO statement is not working in C# , trying to insert into an Access database

I've been trying to insert data into a MS Access database and I can't see what is wrong with my insert statement. I checked all the values and they should be the same, I even tried a really simple statement with static values but it doesn't work anyways.
I've followed the syntax to the letter but I still keep getting an INSERT INTO error when I get to the cmd.ExecuteNonQuery() command.
string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\B8328\source\repos\KaihatsuEnshuu\KaihatsuEnshuu\OI21Database1.accdb";
OleDbConnection con = new OleDbConnection(str);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO order (orderEmpno, orderCustomerId) VALUES (#orderEmpno, #orderCustomerId)";
cmd.Parameters.AddWithValue("#orderEmpno", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#orderCustomerId", comboBox2.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("An order has been started");

How to update ms access database with parameters c#

I am trying to update my ms access db with windows application and I am having a hard time. When I run it I don't get any errors but it does update like once or twice when I test it but then doesn't work again if I do it again a third time.
This is the code I use
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE TABLE SET c_qty=#qty WHERE id = #ID";
Command.Parameters.AddWithValue("#qty", txtQty.Text);
Command.Parameters.AddWithValue("#ID", txtID.Text);
Command.ExecuteNonQuery();
Conn.Close();
I felt I was doing this right or on the right track of having it correct but seems to be more of a issue then I thought. Any help would be great
Quantity and Id are hopefully integers and you should pass them as such.
Also Table is a reserved word, if this really is the name of your table you should enclose it with square brackets.
You should also pass in the correct db types in your parameters and not use AddWithvalue which does not allow this.
Code
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE [TABLE] SET c_qty= ? WHERE id = ?";
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
Conn.Close();
Finally use using blocks for your Disposables. If you were to get an Exception here then connection would remain open until Garbage collection runs which means you might have a problem with other connection attempts to this Access database.
Revised with using blocks
using (OleDbConnection Conn = new OleDbConnection("connectionStringHere"))
using (OleDbCommand Command = new OleDbCommand("UPDATE [TABLE] SET c_qty= ? WHERE id = ?", Conn))
{
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
Conn.Open();
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
}
Finally OleDbCommand does not support named parameters, see OleDbCommand.Parameters

SqlCeCommand Parameters not working

I have a SQL Server Compact database and I'm trying to insert a record into it using cmd.ExecuteNonQuery(). This method worked perfectly fine in another project, but it doesn't work now.
private void AddNewProfile() {
try {
using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.dbConnectionString)) {
using(SqlCeCommand cmd = new SqlCeCommand()) {
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription) VALUES ('#name', '#path', '#desc');";
cmd.Parameters.AddWithValue("#name", SqlDbType.Text).Value = "New Profile";
cmd.Parameters.AddWithValue("#path", SqlDbType.Text).Value = "C:\\";
cmd.Parameters.AddWithValue("#desc", SqlDbType.Text).Value = "A blank profile.";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}
The problem comes in with the parameters - I practically copied the code from one of my other projects, but it doesn't work correctly. Instead of executing this:
INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription)
VALUES ('New Profile', 'C:\\', 'A blank profile.');
it executes this:
INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription)
VALUES ('#name', '#path', '#desc');
What is the problem here?
Two problems:
Firstly, your SQL is specifying literal values because of the quotes. It should be:
INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription)
VALUES (#name, #path, #desc)
That way the SQL refers to the parameters, rather than literals with values of `"#name", "#path" and "#desc".
(I've removed the unnecessary semi-colon as well.)
Secondly, calling AddWithValue, but providing the type as the value, then overwriting the value. That's pointless and confusing - the type you're specifying is going to be lost. You should be using:
cmd.Parameters.Add("#name", SqlDbType.Text).Value = "New Profile";
Finally, you don't need to call conn.Close() - it's already in a using statement... and you can pass conn to the SqlCeCommand constructor, to make things slightly simpler.
You don't need to use single quotes when you declare your parameters. With single quotes, SQL will recognize them as a string literal not parameters. Just use them in your SqlCommand like;
INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription)
VALUES (#name, #path, #desc)
Also you are using AddWithValue in a wrong way. It doesn't need the type.
cmd.Parameters.AddWithValue("#name", "New Profile");
cmd.Parameters.AddWithValue("#path", "C:\\");
cmd.Parameters.AddWithValue("#desc", "A blank profile.");
or you can use Add if you want to declare their types like;
cmd.Parameters.Add("#name", SqlDbType.Text).Value = "New Profile";
cmd.Parameters.Add("#path", SqlDbType.Text).Value = "C:\\";
cmd.Parameters.Add("#desc", SqlDbType.Text).Value = "A blank profile.");
And your conn.Close(); is redundant. The using statement will take care of it for you. Under the hood, SqlConnection.Dispose() calls the SqlConnection.Close() method.
Problem 1: You are enclosig the parameters (#name, #path, #desc) within single quotes, so that you are passing the values as #name, #path, #desc .
Solution 1: You should not enclose the Parameters within single quotes while using Parameterised queries.
Replace This:
cmd.CommandText = "INSERT INTO Profiles (ProfileName, ProfilePath,
ProfileDescription) VALUES ('#name', '#path', '#desc');";
With This:
cmd.CommandText = "INSERT INTO Profiles
(ProfileName, ProfilePath, ProfileDescription)
VALUES (#name, #path, #desc);";
Problem 2: you need to provide both parameter name and its value to the Parameters.AddWithValue() method
Solution 2:
Replace This:
cmd.Parameters.AddWithValue("#name", SqlDbType.Text).Value = "New Profile";
cmd.Parameters.AddWithValue("#path", SqlDbType.Text).Value = "C:\\";
cmd.Parameters.AddWithValue("#desc", SqlDbType.Text).Value = "A blank profile.";
With This:
cmd.Parameters.AddWithValue("#name","New Profile");
cmd.Parameters.AddWithValue("#path","C:\\");
cmd.Parameters.AddWithValue("#desc","A blank profile.");
Complete Code:
private void AddNewProfile() {
try {
using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.dbConnectionString)) {
using(SqlCeCommand cmd = new SqlCeCommand()) {
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Profiles (ProfileName, ProfilePath,
ProfileDescription) VALUES (#name,#path, #desc);";
cmd.Parameters.AddWithValue("#name","New Profile");
cmd.Parameters.AddWithValue("#path","C:\\");
cmd.Parameters.AddWithValue("#desc","A blank profile.");
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}

Categories

Resources