Code Doesn't work. C# Execute Non Query - c#

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.

Related

Message=Incorrect syntax near ')'. Source=Core .Net SqlClient Data Provider

I am trying to load csv into my database but I keep getting the following exception
Message=Incorrect syntax near ')'
My code block is as shown below.
var lineNumber = 0;
using (SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-3EHXXXX;Initial Catalog=XXX_XXXX_Monitoring;Integrated Security=True"))
{
conn.Open();
using (StreamReader reader = new StreamReader(#"C:\\Users\\xxx\\Documents\\XXX\\XXX DATA\\xxxxx_xxxx_2011.csv"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if(lineNumber !=0)
{
var values = line.Split(',');
Console.WriteLine("Before DB Insertion");
var sql = "INSERT INTO XXXXXXX_Monitoring.dbo.LimsDataLists VALUES ('" + values[0] + "','" + values[1] + "','" + values[2] + "','" + "','" + values[3] + "','" + values[4] + "','" + values[5] + "','" + values[6] + "','" + values[7] + "','" + values[8] + "','" +
values[9] + "','" + values[10] + "','" + values[11] + "','" + values[12] + "','" + values[13] + "','" + values[14] + "','" +
values[15] + "','" + values[16] + "','" + values[17] + "','" + values[18] + "','" + values[19] + "','" + values[20] + "','" +
values[21] + "','" + values[22] + "','" + values[23] + "','" + values[24] + "','" + values[25] + "','" + values[26] + "','" +
values[27] + "','" + values[28] + "','" + values[29] + "','" + values[30] + "','" + values[31] + "','" + values[32] + "','" +
values[33] + "','" + values[34] + "','" + values[35] + "','" + values[36] + "','" + values[37] + "'," + values[38] + ")";
var cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
lineNumber++;
}
}
conn.Close();
}
Console.WriteLine("Data import Complete!");
Console.ReadLine();
If you don't want to use EF you can use SqlParameter instead plain query text:
var sqlParams = new List<object>();
var valuesList = new List<string>();
for (int i = 0; i < values.Length; i++)
{
sqlParams.Add(new SqlParameter($"#Value{i}", values[i]));
valuesList.Add($"#Value{i}");
}
var sql = $"INSERT INTO EMR_LIMS_Monitoring.dbo.LimsDataLists VALUES ({ string.Join(", ", valuesList)})";
cmd.Parameters.AddRange(sqlParams);
I suspect that error lies in the sql variable. So, you need to debug your code to catch the string value that the sql variable has. And then run the sql string value somewhere in SQL IDE. Hope that this way you will find where he got stuck into; it's probably a syntax error in your INSERT INTO query.

how to solve error Number of query values and destination fields are not the same. in c# windows application

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();

Insert NEW RECORD to PostgreSQL Line by Line in C#

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!

Insert Query in C# with MS access Database

When I am inserting data in MS access database .it is not giving any error but data not inserted in database
code:
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,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() + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "','" + DateTime.Today + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
MessageBox.Show(str);
//if (dd > 0)
{
MessageBox.Show("Data Saved Successfully..!!!");
}
}
}
Code:
public static int excuteQuery(string q)
{
int d = 0;
try
{
OleDbCommand cmd = new OleDbCommand(q, con);
d = cmd.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return d;
}
if you are using DataContext (you provided to little info)
you should rewrite your statement to match the example:
var customers = db.ExecuteQuery<Customer>(#"SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City, Region, PostalCode, Country, Phone, Fax
FROM dbo.Customers
WHERE City = {0}", "London");
I should suggest to use this tutorial for the connection instead actually

unable to insert data in MS access database using c# windows application

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

Categories