Inserting values into database multiple tables through C# windows application - c#

private void btnsave_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=ABC;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
con.Open();
string savequerybscs="insert into bscs values('"+txtapplicantnumber.Text+"','"+txtname.Text+"','"+txtfathername.Text+"','"+txtmatrictotal.Text+"','"+txtmatricobtained.Text+"','"+txtmatricpercent.Text+"','"+txtintertotal.Text+"','"+txtinterobtained.Text+ "','"+txtinterpercent.Text+"')";
string savequerybsit ="insert into bsit values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "')";
string savequerymcs ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','"+txtbachelortotal.Text+"','"+txtbachelorobtained.Text+"','"+txtbachelorpercent.Text+"')";
string savequerymit ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','" + txtbachelortotal.Text + "','" + txtbachelorobtained.Text + "','" + txtbachelorpercent.Text + "')";
SqlCommand cmd = new SqlCommand(savequerybscs,savequerymcs,bla blaa);
}
As you can see, this solution is pretty messed up. Is there any other way to handle such issues? All I want is to insert data in multiple tables simultaneously but SqlCommand only takes 1 argument.
I just learned about bulk query or bulk insertion. Can someone guide me through that? I am not clearly getting those concepts from youtube.

You can do one insert query using the comma separator between tuples for multiples rows:
insert into bsit values (field1, field2...), (field1, field2...), ...
But this insert is for one table.
Basically, you use as many SQL query as many table you want to update.
I'm not advanced but perhaps, depending on the database server, you could execute a "script" in one C# SqlCommand execute non query call, using the semilicon separator, like:
string sql = "insert into table1 values (field1, field2...), (field1, field2...), ... ; "
+ "insert into table2 values (field1, field2...), (field1, field2...), ... ;";
MySql should support that.
You should use SQL Parameters for security reason instead of adding values to the sql string itself:
string sql = "insert into table1 values (?, ?)";
var command = new OdbcCommand(sql, connection);
command.Parameters.Add("#ID", OdbcType.Text).Value = Guid.NewGuid().ToString();
command.Parameters.Add("#Name", OdbcType.Text).Value = "Test";
command.ExecuteNonQuery();
https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlcommand.parameters

Related

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

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

inserting data from excel to sql table

Am getting an error while inserting data from excel to the database table.
this is the error Incorrect syntax near 'NAME'
this is my code:
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
conStr = ConfigurationManager.ConnectionStrings["SqlConString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("insert into MedicalItems (ITEM NAME,GROUP,ITEM TYPE,COST PRICE,SELLING PRICE,PURCHASE UOM,PURCHASE PACKAGING,DISPENSING UOM,QTY ON HAND,EXPIRY DATE,REORDER LEVEL,REORDER QUANTITY,BATCH#) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Label2.Text = "Records inserted successfully";
}
Wrap the column names within [] like [ITEM NAME], for all the columns with whitespaces.

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!

Code Doesn't work. C# Execute Non Query

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.

Categories