Cannot Find Table 0 from other form - c#

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).

Related

How to insert data into multiple SQL Server tables using 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();
}

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

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 ','.

save checkbox value in access database with vb.net 2010 (wpf c#)

guy how can i insert the value of checkbox in access database or any database.
i tried any of this sql statement but it still give me error: OleDbException was Unhandled. Data type mismatch in criteria expression. and it's pointing to myData = myCommand.ExecuteReader();
note that allowviewpsr is a boolean type of field in ms access database or the one with YES/NO. :) chkviewpsr is mycheckbox
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and here's my connector:
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.SelectCommand = myCommand;
myData = myCommand.ExecuteReader();
EDITED:
hi anandkumar thanks for the quick replay i tried NonQuery but it gives same error as above
SQL = "UPDATE `RWMUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Snapshot of my Access Database :(
Instead of
myAdapter.SelectCommand = myCommand;
myCommand.ExecuteReader();
Use
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Reference:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx

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