How to insert data into multiple SQL Server tables using C#? - c#

I'm new joined this site. I have a little bit of a C# problem. I need to know how to insert data into multiple SQL Server tables using C#. English is not my mother language, so sorry if there are some spelling mistakes.
This is my C# code
try
{
Sqlconn.Open();
SqlCommand cmd = Sqlconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into New_Vehicle values ('" + txt_id.Text + "', '" + txtV_No.Text + "', '" + txtE_No.Text + "', '" + dtm_Year.Text + "')";
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into New_Brand values ('" + txt_id.Text + "', '" + txtB_Name.Text + "', '" + txt_Model_Name.Text + "', '" + txtV_Type.Text + "')";
cmd.ExecuteNonQuery();
Sqlconn.Close();
MessageBox.Show("Seve Record Succesfull", "Insert Message");
}
catch (Exception EX)
{
MessageBox.Show("Error" + EX);
}
This is the error I get when I run this code. Please help how to fix this problem

I would loop through each table with a foreach loop and run the insert code you have there but use the table name from the foreach loop
for this to work, you would need a list of table objects, each with a property called "Name" which contains the name of the table that matches the table name in the database
foreach (var table in List_Of_Tables)
{
cmd.CommandText = "insert into " + table.Name + " values ('" + txt_id.Text + "', '" + txtV_No.Text + "', '" + txtE_No.Text + "', '" + dtm_Year.Text + "')";
cmd.ExecuteNonQuery();
}

Related

Cannot Find Table 0 from other form

Tried to move data from one form to another and there is a problem with the table. Yes I found such themes with a mistake, and tried to correct himself, but something went wrong.
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
You are expecting results to be returned from your query, but what you do is just INSERT statement.
For inserting values you should use ExecuteNonQuery method of SqlCommand (see this for reference).
Then, assign another command: SELECT to get the results, then you can fill DataSet with the result and then you can fill DataGridView with it.
Also: you are rpone to SQL injection, use parametrized query to prevent yourself from such threat (see this for reference).

how to add check in access database using checkbox (not value of Checkbox)

with this code without adding checkbox its working properly
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into StudentInformation ([StudentID], [Lastname], [Firstname], [Middle initial], [Course], [Year], [Sem]) values ('" + txtStudentID.Text + "' , '" + txtStudentFN.Text + "','" + txtStudentFN.Text + "','" + txtStudentMI.Text + "','" + txtCourse.Text + "','" + txtYear.Text + "','" + txtSem.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Added Successfully!");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
but when i add checkbox
"insert into StudentInformain ([StudentID], ..... [Transferee] values ('" + txtStudentID.Text + "' ,...... '" + CheckBoxTrans + "')";
i got an error
sorry for my bad english
how do i add check in my database
(note not value of checkbox)

INSERT query error: Number of query values and destination fields are not the same

protected void Button1_Click1(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/WEB/App_Data/mydata.accdb");
OleDbCommand com = new OleDbCommand("insert into player_reg (p_name,f_name,dob,pob,sex,marital,nation,address,address,state,mob,email,course,college,y_year,sports,voter) values ('" + TextBox1.Text + "', '" + TextBox2.Text + "','" + TextBox3.Text + "', '" + TextBox4.Text + "','" + TextBox5.Text + "', '" + TextBox6.Text + "','" + TextBox7.Text + "', '" + TextBox8.Text + "','" + TextBox9.Text+ "', '" + TextBox10.Text + "','" + TextBox11.Text + "', '" + TextBox12.Text+ "','" + TextBox13.Text+ "', '" + TextBox14.Text + "''" + TextBox15.Text + "', '" + TextBox16.Text + "')", con);
con.Open();
com.CommandType = CommandType.Text;
com.ExecuteNonQuery();
Response.Write("values inserted successfully");
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
You have adress 2 times in your query, delete it.
OleDbCommand com = new OleDbCommand("insert into player_reg (p_name,f_name,dob,pob,sex,marital,nation,
address,address,state,mob,email,course,college,
y_year,sports,voter) values ...
There are 17 items in the columns list but only 16 items in the VALUES list. In the columns list you repeated address twice.
While I have your attention, constructing SQL statements by "gluing together" raw user input (textbox.Text values) is very bad practice. You should use a parameterized query instead.
con.Open();
OleDbCommand com = new OleDbCommand(
"insert into player_reg (p_name, f_name, dob, pob, sex, marital, nation, address, state, mob, email, course, college, y_year, sports, voter)" +
"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", con);
com.Parameters.AddWithValue("?", TextBox1.Text); // p_name
com.Parameters.AddWithValue("?", TextBox2.Text); // f_name
com.Parameters.AddWithValue("?", TextBox3.Text); // dob
// ...and so on...
com.Parameters.AddWithValue("?", TextBox16.Text); // voter
com.ExecuteNonQuery();
con.Close();
Field address is repeated in your query -- the number of columns must be equal to number of values in "VALUES" clause separated by ','.

Update Statement will not update table

I'm trying to update a vendor record in a MS Access table and this is the code if have in the DA layer:
method to update the vendor
public static void updateVendor(Vendor aVendor)
{
try
{
String sSQLCommand = "UPDATE Vendor SET VendorID = '" + aVendor.VendorId + "', VendorName = '" + aVendor.Name
+ "', AddressNo = '" + aVendor.AddressNo + "', Address = '" + aVendor.Address + "', City = '"
+ aVendor.City + "', State = '" + aVendor.State + "', ZipCode = '" + aVendor.Zipcode + "', PhoneNumber = '"
+ aVendor.PhoneNumber + "' WHERE VendorID = '" + aVendor.VendorId + "'";
// Create the command object
if (aConnection.State == ConnectionState.Closed)
aConnection.Open();
OleDbCommand cmd = aConnection.CreateCommand();
cmd.CommandText = sSQLCommand;
// Execute the SQL command
cmd.ExecuteNonQuery();
aConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I'm not getting any kind of error, but it will not update the table, so I'm not sure what is wrong about it, do you see anything that is wrong?
Daniel, if the query is executing without any error and the issue is that no record is updated then check following in data:
VendorID field is text field, so if it's having white space preceding the value in the column then your query will not update any thing but execute successfully.
It's possible because access does n't remove the preceding white space in text.

Using select scoped value in insert statements?

Note: I'm building a practice project where my trainer has forbid me to parameterize. I am aware of the security risks, but the site will not be deployed. I'm using a select scope_identity method to grab an auto-incremented value from the SubmissionId column of my table Submissions.
I want to insert that value into two other tables; I've got newSubID declared as a var and I use it in the insert statements, but I get the error message
The name "newSubID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
What am I missing here?
Here's my code:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String subQuery = "INSERT INTO Submission (Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments) VALUES ('" + TbCoverage.Text + "','" + TbCurrentCoverage.Text + "','" + TbPrimEx.Text + "','" + TbRetention.Text + "','" + TbEffectiveDate.Text + "','" + TbCommission.Text + "','" + TbPremium.Text + "','" + TbComments.Text + "')"
+ "SELECT CAST (SCOPE_IDENTITY() AS int)";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
SqlCommand subCmd = new SqlCommand(subQuery, sqlConn);
using (subCmd)
{
subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity, CustState, CustZip, SubId) VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem + "', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" + DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "', newSubID)";
String broQuery = "INSERT INTO Broker (BroId, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, SubId) VALUES ('" + TbBroId.Text + "', '" + TbBroName.Text + "', '" + TbBroAddress.Text + "', '" + TbBroCity.Text + "', '" + DdlBroState.SelectedItem + "', '" + TbBroZip.Text + "', '" + DdlEntity.SelectedItem + "', newSubID)";
SqlCommand custCmd = new SqlCommand(custQuery, sqlConn);
SqlCommand broCmd = new SqlCommand(broQuery, sqlConn);
using (custCmd)
using (broCmd)
{
custCmd.ExecuteNonQuery();
broCmd.ExecuteNonQuery();
Response.Redirect("~/View.aspx?ProductId=" + newSubID);
}
This is called up on the next page like so (I have left the errors as they are in the interest of helping whomever may need to see the problem and solutions, which are listed in answers below):
string x = Request.QueryString["SubmissionId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string editCustQuery = "SELECT CustName, SicNaic, CustCity, CustAdd, CustState, CustZip FROM Customer WHERE SubId =" + x;
using (SqlConnection editConn = new SqlConnection(connectionString))
{
editConn.Open();
using (SqlCommand CustCommand = new SqlCommand(editCustQuery, editConn))
{
SqlDataReader dr = CustCommand.ExecuteReader();
dr.Read();
LblCustName.Text = dr.GetString(0);
LblSicNaic.Text = dr.GetString(1);
LblCustCity.Text = dr.GetString(2);
LblCustAddress.Text = dr.GetString(3);
LblCustState.Text = dr.GetString(4);
LblCustZip.Text = dr.GetInt32(5).ToString();
}
It's because you're not concatenating the newSubID into the custQuery / btoQuery SQL statements, but instead your using the literal text "newSubID" in the statement which is invalid here as it will assume "newSubID" is a column name.
i.e.
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity,
CustState, CustZip, SubId)
VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem +
"', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" +
DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "'," +
newSubID.toString() + ")";
Of course, I'm only giving an answer that uses dynamic SQL like this because of your disclaimer and is not what I'd do in real life!
Answer of AdaTheDev is correct.
I think you have another issue. If you do ExecuteNonQuery and then ExecuteScalar with the same command, you'll insert twice. Use an out-parameter for your scope_id and call only exenonquery or call just exescalar.
//subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();

Categories