I have tried to insert data in MS access database but data is not added in database and error not given.
private void btnsubmit_Click(object sender, EventArgs e)
{
int row = dataGridView1.RowCount;
for (int i = 0; i < row - 1; i++)
{
String str = "INSERT INTO JDS_Data(job_no,order_no,Revision,DesignSpec,Engine_Type,Record_date,LE_IN_Designer,CPH_Designer,Exp_Del_Week,Action_code,Rev_Description,Ref_pattern,Name_of_mock_up,EPC_Drawing,Turbocharger_no_Type,Engine_Specific_Requirement,Draft_sketch_with_details,Air_cooler_type,Description_of_Job,SF_No,Standard,Prority_Sequence,Remark,Part_family,Modified_Date,User) values('" + txtjobno.Text + "','" + txtorderno.Text + "','" + txtrevison.Text + "','" + txtds.Text + "','" + txtenginetype.Text + "','" + dateTimePicker1.Text + "','" + txtleindesigner.Text + "','" + txtcphdesigner.Text + "','" + txtexpweek.Text + "','" + txtactioncode.Text + "','" + txtrevdescription.Text + "','" + txtrefpatern.Text + "','" + txtmockup.Text + "','" + txtepcdwg.Text + "','" + txtturbono.Text + "','" + txtenginereq.Text + "','" + txtdraft.Text + "','" + txtaircolertype.Text + "','" + txtdespjob.Text + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtremark.Text + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + DateTime.Today + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
MessageBox.Show(str);
//if (dd > 0)
{
MessageBox.Show("Data Saved Successfully..!!!");
}
}
}
Hey your query have Syntax error use below line
String str = "INSERT INTO JOB_Quality_Rating(Team,JOB_Type,Designer_Name,AUR_NO,Task_No,Sub_Function_no,Severity_Level,Checkpoints,Points_Deducted,Total_Points,Submitted_By,Submitted_Date) values('" + comboBox1.SelectedItem + "','"+comboBox7.SelectedItem+"','" + comboBox3.SelectedItem + "','" + comboBox6.SelectedItem + "','" + cmbtaskno.SelectedItem + "','" + comboBox2.SelectedItem + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtTotal.Text + "','" + mdlconnection.user_name + "','" + dateTimePicker1.Text + "')";
Instead of
String str = "INSERT INTO JOB_Quality_Rating(Team,JOB_Type,Designer_Name,AUR_NO,Task_No,Sub_Function_no,Severity_Level,Checkpoints,Points_Deducted,Total_Points,Submitted_By,Submitted_Date) values('" + comboBox1.SelectedItem + "',,'"+comboBox7.SelectedItem+"','" + comboBox3.SelectedItem + "','" + comboBox6.SelectedItem + "','" + cmbtaskno.SelectedItem + "','" + comboBox2.SelectedItem + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtTotal.Text + "','" + mdlconnection.user_name + "','" + dateTimePicker1.Text + "')";
Hope it helps.
Probably your syntax is incorrect. Constructing query with string concatenation is always a bad idea. Use parametrized query string with built-in parameter values handling via OdbcCommand.Parameters.Add(...).
cyberj0g is right, your syntax is incorrect. Particularly, you've got a value missing in your values list at around here: ...comboBox1.SelectedItem + "',,'"+comboBox7.SelectedItem.... You can't pass an empty value this way. Either pass NULL here or remove the respective field form the field list clause: ...Team,Designer_Name... (and the extra comma too, or course).
You can try the following -
- Try executing the query string (what is formed in str variable) manually in access to make sure there are no errors in he syntax and it executes there successfully
- Wrap the execution statement in try..catch block to get error detail
- Make sure the connection is pointing to the correct database instance
Related
how to solve error Number of query values and destination fields are not the same. in c# windows application
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
cmd.CommandText = "Insert into purchase(Bill_No,Tax_Invoice_No,Date,Supplier_ID,Supplier_Name,Supplier_GST_No,Product_ID,Product_Name,Product_Type,Product_Price,Product_Qty,Amount,Gross_Total,CGST,SGST,Total,Round_Off,Final_Total,Bill_Detail) values('" + Bill_No.Text + "','" + Tax_Invoice_No.Text + "','" + Date.Text + "','" + Supplier_ID.Text + "','" + Supplier_Name.Text + "','" + Supplier_GST_No.Text + "','" + dataGridView3.Rows[i].Cells["Product_ID"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Name"].Value +"','" + dataGridView3.Rows[i].Cells["Product_Type"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Price"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Qty"].Value + "','" + dataGridView3.Rows[i].Cells["Amount"].Value + "','" + Gross_Total.Text + "','" + CGST.Text + "','" + SGST.Text + "','" + Total.Text + "','" + Round_Off.Text + "','" + Final_Total.Text + "','" + Bill_Detail.Text + "')";
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
database table
Click Here to View Dataabase
make sure that the Database table(purchase) value are the same with your array.
afterthought:
Query should be : Insert into purchase(table columns) values();
Good day!
I am a newbie in C#.NET (I came from VB6).
I want to Insert new record to my database using PostgreQL.
I can use a single line of code, like:
Insert into table1 values("value1","value2","value3");
But I wanted to insert new record line by line, like:
rs.open("Select * from table1",con,AdOpenDynamic, AdLockOptimistic)
rs.Fields("Field1").value = value1
rs.Fields("Field2").value = value2
rs.Fields("Field3").value = value3
rs.Update
Again, I am a newbie here. Also again, I can insert using a single INSERT statement.
But IF I have 40 Fields, the code is hard to read (for readability). If the code is line by line, it is easy to read and the code is easy to update.
Is there any way to do it? Any help will be appreciated!
Happy Coding!
Even Postgres:
Code doesn't change it still
Insert into tablename(field1,field2,field3 and so on....) values(value1,value2,value3 and so on...)
Here's the workaround:
string connectionString = "Your connection string here";
protected static int ExecuteQuery(string query)
{
using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
{
con.Open();
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
int result = cmd.ExecuteNonQuery();
return result;
}
}
}
To use this:
ExecuteQuery("Insert into tablename(field1,field2,field3 and so on....) values(value1,value2,value3 and so on...)")
Thanks #reds for the Answer and suggestions. I realized my only problem is the code readability, not the code itself. As you have said, Insert Query is the best workaround. That's why I came up with the following structure:
////saving
//CODE TO DATABASE
NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=sdferekrjsdf873()#3s;Database=DB");
iConnect.Open();
NpgsqlCommand iQuery = new NpgsqlCommand
("insert into tblstudents_secure values('" +
myModule.studID + "','" +
myModule.studFname + "','" +
myModule.studMname + "','" +
myModule.studLname + "','" +
myModule.studGrade + "','" +
myModule.studSection + "','" +
myModule.studHomeAdd + "','" +
myModule.studProvAdd + "','" +
myModule.studBday + "','" +
myModule.studAge + "','" +
myModule.studCivilStat + "','" +
myModule.studHomeContact + "','" +
myModule.studProvContact + "','" +
myModule.studBplace + "','" +
myModule.studGender + "','" +
myModule.studReligion + "','" +
myModule.studFather + "','" +
myModule.studFatherOcc + "','" +
myModule.studMother + "','" +
myModule.studMotherOcc + "','" +
myModule.studGuardian + "','" +
myModule.studGuardianOcc + "','" +
myModule.studGuardianRel + "','" +
myModule.studGuardianContact + "','" +
myModule.studOldSchool + "','" +
myModule.studOldSchoolAdd + "','" +
myModule.studOldGrade + "','" +
myModule.studOldSY + "','" +
myModule.studIsTransfer + "','" +
myModule.studHas137 + "','" +
myModule.studHas138 + "','" +
myModule.studHasGoodMoral + "','" +
myModule.studHasNSO + "','" +
myModule.studHasMed + "','" +
myModule.studRemarks + "','" +
myModule.studDateRegistered + "','" +
myModule.studEnrollmentStatus + "')", iConnect);
iQuery.ExecuteNonQuery();
iConnect.Close();
Where:
`
myModule
is a class handler of static strings studID, studFname, etc...
Happy Coding!
string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;
conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial Catalog=DBMSI;Integrated Security=True";
sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";
cnn = new SqlConnection(conStr);
try
{
cnn.Open();
cnn = new SqlConnection(conStr);
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Open();
MessageBox.Show("Employee Details registered Succesffuly");
// Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program.
}
catch (Exception ex)
{
MessageBox.Show("Error Occoured - Employee Details were not recorded");
}
Found the code online. Please help to make it work. Thanks!
Hopefully your primary key on CEC_Employee isn't "empid", and if it is set to be an autonumber, like IDENTITY(1,1), the SQL command will fail as it won't let you hand it a primary key value.
This is speculation of course, since you haven't posted the actual exception message or stack trace.
I want to get id after I insert a row of data into a table but I get an error:
System.InvalidCastException: Specified cast is not valid.
This is my code
SqlCommand cmd_insert = new SqlCommand("insert into ITM_OrderItem (ITM_Code, ITM_Desc, ORCAT_Desc, ORSCT_Desc, ARCBG_Abbrev, ARCSG_Desc, ARCSC_Code, ARCIM_DerivedFeeItem, OPD_Price, IPD_Price, Tou_Price, App_Status, SITES, CSSUSR_RowId, CSSUSR_DepId, CSSUSR_PosId , CDate, MDate) values('"
+ dt.Rows[i]["EARCIM_Code"].ToString() + "','"
+ dt.Rows[i]["EARCIM_Desc"].ToString() + "','"
+ dt.Rows[i]["EORCAT_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCIC_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCBG_Abbrev"].ToString() + "','"
+ dt.Rows[i]["EARCSG_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCSC_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCIM_DerivedFeeItem"].ToString() + "','"
+ dt.Rows[i]["OPD"].ToString() + "','"
+ dt.Rows[i]["IPD"].ToString() + "','"
+ dt.Rows[i]["Tourist"].ToString() + "','"
+ status_app + "','"
+ usr_site + "','"
+ usrID + "','"
+ Dep_RowId + "','"
+ Pos_RowId + "','"
+ Cdate + "','"
+ Cdate + "') select SCOPE_IDENTITY()", conEMR);
// error on this line
insert_RowId = (Int32)cmd_insert.ExecuteScalar();
Thank you a lot.
It looks as if the identity column in your table ITM_OrderItem does not use int as data type, What I can guess is that it is a bigint data type and if that is the case you should change the line in your code to:
insert_RowId = (Int64)cmd_insert.ExecuteScalar();
Also make sure that you change the datatype of variable 'insert_RowId' to Int64 in your C# code declaration.
Here is my code
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
sqlCmd.CommandText = "INSERT INTO ChheckOut(rakmsheek,tare5sheek,esmsa7bsheek,mablgh,hesab,esmel7sab,mla7zat,rakmkeed,tare5,rakmel3mel,segldareby,most5dm,rakm7araka,madfo3nakdan,madfo3bshikat,magmo3shikat,mgmo3nakdanwshikat,khasmelmosder,mablgh7esab,esmel3mel,addresso) VALUES ('"
+ dataGridView1.Rows[i].Cells["Column1"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column2"].Value + "','"
+ dataGridView1.Rows[i].Cells["Column3"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column4"].Value + "',' "
+ dataGridView1.Rows[i].Cells["Column5"].Value + "',' "
+ dataGridView1.Rows[i].Cells["Column6"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column7"].Value + "','"
+ maskedTextBox1.Text + "','" + maskedTextBox19.Text + "','"
+ maskedTextBox3.Text + "','" + maskedTextBox4.Text + "','"
+ maskedTextBox12.Text + "','" + maskedTextBox13.Text + "','"
+ maskedTextBox6.Text + "','" + maskedTextBox10.Text + "','"
+ maskedTextBox7.Text + "','" + maskedTextBox9.Text + "','"
+ maskedTextBox8.Text + "','" + maskedTextBox11.Text + "','"
+ textBox1.Text + "','" + textBox2.Text + "');";
sqlCmd.ExecuteNonQuery();
db.SaveChanges();
}
Not full rows insert into the database I don't know why. And its random, not the same data left every time :(
What does your table schema look like? Also, what is some sample data you are trying to insert?
If the insert is succeeding, but the data stored isn't what you were expecting, it's probably not inserting null into not null. If the only fields not showing up are datetime data types, that might be a huge clue. Make sure you are actually trying to insert the correct datatypes.