Update Statement will not update table - c#

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.

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

No errors in the code, but no changes occur in the table when trying to update it

I'm trying to update my data in C# Win Form.
I created a button "update", but whenever I run it, I don't see any changes in the table and any occurring errors
void insertdata() {
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM airport";
adapter.SelectCommand = cmd;
table.Clear();
adapter.Fill(table);
dgv.DataSource = table;
}
private void button_update_Click(object sender, EventArgs e)
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE airport SET p_name = '"+textBox2.Text+ "',p_age = '" + textBox3.Text + "', c_name = '" + textBox4.Text + "', date = '" + textBox5.Text + "', city_t = '" + textBox6.Text + "', city_f ='" + textBox7.Text + "', trip_num = '" + textBox8.Text + "', plane_type = '" + textBox9.Text+"' WHERE p_id = '"+textBox1+"'";
cmd.ExecuteNonQuery();
insertdata();
}
I've tried to add
connection.Open();
connection.Close();
However, I keep getting: "System.InvalidOperationException: "The connection was not closed. The connection is open."
Could there be any change in my code for updating the rows in the table, as whenever I run it I don't get any errors.
Please note the you wrote
WHERE p_id = '"+textBox1+"'
Instead of
WHERE p_id = '"+textBox1.Text+"'
Probably you don't have an ID that equals to the textBox...

Where is the error in my syntax? Getting values from SQL Server database

I am trying to read an integer from a SQL Server database by text in comboboxes.
I get a "Syntax error" "near" my Table name "Seeweg". The debugger does not highlight the line, where the error happens.
The column with the value I like to get is named seadistance. The other columns, by which to sort are start and ziel.
They get sorted by the values written in the comboboxes.
To reproduce this procedure I inserted the code into a class and called the instance by a button named btnSea.
I already searched for similar problems, but I could not find any syntax errors concerning the string implementation. The column names are correct.
//The Button
private void btnSea_Click(object sender, EventArgs e)
{
Entnehmen CO2 = new Entnehmen();
int Dist = CO2.Werte("Seeweg", "start", "ziel", "seadistance", comboSeaOrig.Text, comboSeaDest.Text);
MessageBox.Show(Dist.ToString());
}
//The class
class Entnehmen
{
public int Werte(string Tabelle, string Reihe1, string Reihe2, string Wertereihe, string WertReihe1, string WertReihe2)
{
int Wert = 0;
string myConnection = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection myConn = new SqlConnection(myConnection))
{
myConn.Open();
SqlCommand SelectCommand = new SqlCommand("SELECT '" + Wertereihe + "' FROM '" + Tabelle + "' WHERE '" + Reihe1 + "' = '" + WertReihe1 + "' AND '" + Reihe2 + "' = '" + WertReihe2 + "' ; ", myConn);
Wert = (int)SelectCommand.ExecuteScalar();
}
return Wert;
}
}
}
I expect the value to be given back. Before that happens, I get the error:
Incorrect syntex near 'Seeweg'
Where is the syntax mistake? Any help is appreciated =)
You are generating something like:
SELECT 'seadistance' FROM 'Seeweg' WHERE 'start' = 'aa' AND 'ziel' = 'bbb'
This is not a valid T-SQL statement. Correct your quotes in columns and tables variables.
This is a suggestion of how you can write your T-SQL statemant based on your code:
SqlCommand SelectCommand = new SqlCommand("SELECT " + Wertereihe + " FROM " + Tabelle + " WHERE " + Reihe1 + " = '" + WertReihe1 + "' AND " + Reihe2 + " = '" + WertReihe2 + "' ; ", myConn);

Store null integer value from inside c# app

Hie.
So what I'm trying to do is insert a null value in an integer column in MySQL using a C# application.
I'm aware the query to generally do such a thing would be;
INSERT INTO Database.Table (IntColumn) VALUES (NULL);
UPDATE Database.Table set IntColumn = (NULL) where id = '1';
It works great in workbench. Thing is, I'm not even sure if this is possible but I need to do this in C# while still allowing the textbox the flexibility to enter integers into the MySQL database. In this case 'home.text' which is linked up to 'home' column in MySQL which is an integer field.
This is how I made my code.
using MySql.Data.MySqlClient;
using MySql.Data;
namespace Masca.Content
{
/// <summary>
/// Interaction logic for Login.xaml
/// </summary>
public partial class Login : UserControl
{
//Function to check if column value is null before fetching string
public static string GetString(MySqlDataReader reader, string colName)
{
if (reader[colName] == DBNull.Value)
return string.Empty;
else
return (string)reader[colName];
}
//Function to check if column value is null before fetching int as string
public static string GetColumnValueAsString(MySqlDataReader reader, string colName)
{
if (reader[colName] == DBNull.Value)
return string.Empty;
else
return reader[colName].ToString();
}
public Login()
{
InitializeComponent();
}
public void save_Click(object sender, RoutedEventArgs e)
{
//Authentication parameters
string sqlcon = "datasource = localhost; port = 3306; username = root; password = root";
//Query to excecute
string queryadd = "insert into users.employees (member, username, password, question, answer, first, second, third, surname, dob, gender, doc, dept, cell, home, work, email, pemail, street, surbub, city, region, position, access, privilages, bank, account) values ('" + this.member.Text + "','" + this.username.Text + "','" + this.password.Text + "', '" + this.question.Text + "','" + this.answer.Text + "', '" + this.first.Text + "','" + this.second.Text + "','" + this.third.Text + "','" + this.surname.Text + "', '" + this.dob.Text + "','" + this.gender.Text + "', '" + this.doc.Text + "', '" + this.dept.Text + "', '" + this.cell.Text + "','" + this.home.Text + "', '" + this.work.Text + "', '" + this.email.Text + "', '" + this.pemail.Text + "', '" + this.street.Text + "', '" + this.surbub.Text + "', '" + this.city.Text + "', '" + this.region.Text + "', '" + this.position.Text + "', '" + this.access.Text + "', '" + this.privilages.Text + "', '" + this.bank.Text + "', '" + this.account.Text + "') ; insert into logon.login (username, password) values ('" +this.username.Text+ "', '" +this.password.Text+ "'); select * from users.employees where member = '" + this.member.Text + "' ;";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlDataReader rdr;
MySqlCommand cmd = new MySqlCommand(queryadd, con);
// Excecution
try
{
con.Open();
rdr = cmd.ExecuteReader();
MessageBox.Show("Saved");
while (rdr.Read())
{
//Declarations using function
string stag = GetColumnValueAsString(rdr, "tag");
string snumber = GetColumnValueAsString(rdr, "tag");
string smember = GetColumnValueAsString(rdr, "member");
string susername = GetString(rdr, "username");
string spassword = GetString(rdr, "password");
string ssecurity = GetString(rdr, "question");
string sanswer = GetString(rdr, "answer");
string sfirst = GetString(rdr, "first");
string ssecond = GetString(rdr, "second");
string sthird = GetString(rdr, "third");
string sfourth = GetString(rdr, "surname");
string sdob = rdr.GetString("dob");
string sgender = rdr.GetString("gender");
string sdoc = rdr.GetString("doc");
string sdept = rdr.GetString("dept");
string scell = GetColumnValueAsString(rdr, "cell");
string shome = GetColumnValueAsString(rdr, "home");
string swork = GetColumnValueAsString(rdr, "work");
string semail = GetString(rdr, "email");
string spemail = GetString(rdr, "pemail");
string sstreet = GetString(rdr, "street");
string ssurbub = GetString(rdr, "surbub");
string scity = GetString(rdr, "city");
string sregion = GetString(rdr, "region");
string sposition = GetString(rdr, "position");
string saccess = GetString(rdr, "access");
string sprivilages = GetString(rdr, "privilages");
string sbank = GetString(rdr, "bank");
string saccount = GetString(rdr, "account");
//Binding strings to textboxes
tag.Text = stag;
number.Text = stag;
member.Text = smember;
username.Text = susername;
password.Text = spassword;
question.Text = ssecurity;
answer.Text = sanswer;
first.Text = sfirst;
second.Text = ssecond;
third.Text = sthird;
surname.Text = sfourth;
dob.Text = sdob;
gender.Text = sgender;
doc.Text = sdoc;
dept.Text = sdept;
cell.Text = scell;
home.Text = shome;
work.Text = swork;
email.Text = semail;
pemail.Text = spemail;
street.Text = sstreet;
surbub.Text = ssurbub;
city.Text = scity;
region.Text = sregion;
position.Text = sposition;
access.Text = saccess;
privilages.Text = sprivilages;
bank.Text = sbank;
account.Text = saccount;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is the code behind a form that contains employee details. home.text is supposed to hold the home land line number. Assuming the employee doesn't have a land line at home, they would leave the field blank.
Everytime I do that however, I get an exception thrown saying "Incorrect integer value". To leave it blank in the database, I would have to type (NULL) where '"this.home.text'" currently is in the query. If i do that though, I wont be able to insert information into the database using home.text when need be.
Anyother way to do this?
Insert Usual preamble about your SQL being open to injection attacks (see this question for more information on parameterized SQL).
The problem is, you're inserting strings in to all the columns, irrespective of the underlying database type.
this:
'" + this.home.text + "'
If blank, will produce '', which cannot be converted to an integer. You might want to try something like:
int? homeNumber = null; // Note the int? is syntactic sugar for Nullable<int>
if(!string.IsNullOrEmpty(home.text))
homeNumber = Convert.ToInt32(home.Text);
And insert thusly:
," + homeNumber + ",.... etc.
You could try something along the lines of
if (!int.TryParse(shome, out home.Text))
home.Text = null;
I think instead you should just check for empty or null strings,
string queryadd = "insert into users.employees (member, username, password, question, answer, first, second, third, surname, dob, gender, doc, dept, cell, home, work, email, pemail, street, surbub, city, region, position, access, privilages, bank, account) values ('"
+ this.member.Text + "','" + this.username.Text + "','" + this.password.Text + "', '" + this.question.Text + "','" + this.answer.Text + "', '" + this.first.Text + "','" + this.second.Text + "','" + this.third.Text
+ "','" + this.surname.Text + "', '" + this.dob.Text + "','" + this.gender.Text + "', '" + this.doc.Text + "', '" + this.dept.Text + "', '" + this.cell.Text + "','"
+ string.IsNullOrWhiteSpace(this.home.Text) ? null : this.home.Text + "', '"
+ this.work.Text + "', '" + this.email.Text + "', '" + this.pemail.Text + "', '" + this.street.Text + "', '" + this.surbub.Text + "', '" + this.city.Text + "', '" + this.region.Text + "', '" + this.position.Text + "', '"
+ this.access.Text + "', '" + this.privilages.Text + "', '" + this.bank.Text + "', '" + this.account.Text
+ "') ; insert into logon.login (username, password) values ('" + this.username.Text + "', '" + this.password.Text + "'); "
+ " select * from users.employees where member = '" + this.member.Text + "' ;";
look at string.IsNullOrWhiteSpace(this.home.Text) ? null : this.home.Text
I don't think so the SQL that you have formed is right and will work like this, i.e. two SQL separated by ; and also has SELECT SQL merged with INSERT

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