c# Insert data into MySQL database using parameters - c#

This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.

Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);

I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();

when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();

Related

Trying to read data from sql database and show on textboxes - Visual C# (syntax error)

edit: I'm aware of SQL Injection.
First of all, I know my coding methods are terrible but thats what I can for now, extremely beginner on c#.
I'm trying to read data from SQL server and show them on Textboxes.
User going to write (and choose from cmbbox) some data on;
cmbIl.Text, cmbIlce.Text, cmbMahalle.Text, txtAda.Text, txtPafta.Text
and press the button for search.
If that data correspond to the values in sql database (true), some other data will be taken and shown at
txtTapuKodu.Text, txtPafta.Text, txtTapuAlani.Text, txtNitelik.Text,
rtxtImarDurumu.Text
But the code below gives that error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
private void btnSorgula_Click(object sender, EventArgs e)
{
string source = #"Data Source=YAGIZ-PC;Initial Catalog=imar_sorgu;Integrated Security=True";
SqlConnection con = new SqlConnection(source);
con.Open();
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
/* string sqlSelectQuery2 = "SELECT * FROM tablo_arsa WHERE ilce ='" + cmbIlce.Text + "'";
string sqlSelectQuery3 = "SELECT * FROM tablo_arsa WHERE mahalle ='" + cmbMahalle.Text + "'";
string sqlSelectQuery4 = "SELECT * FROM tablo_arsa WHERE ada = " + txtAda.Text;
string sqlSelectQuery5 = "SELECT * FROM tablo_arsa WHERE parsel = " + txtParsel.Text; */
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTapuKodu.Text = (dr["tapu_kodu"].ToString());
txtPafta.Text = (dr["pafta"].ToString());
txtTapuAlani.Text = (dr["tapu_alani"].ToString());
txtNitelik.Text = (dr["nitelik"].ToString());
rtxtImarDurumu.Text = (dr["imar_durumu"].ToString());
MessageBox.Show("İstek başarıyla okundu.");
}
else
{
MessageBox.Show("Okuma başarısız.");
}
con.Close();
}
The problem is that your where clause contains commas between the predicates. use AND instead.
change:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
to:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "' AND ilce = '" + cmbIlce.Text + "' AND mahalle = '" + cmbMahalle.Text + "' AND ada = '" + txtAda.Text + "' AND parsel = '" + txtParsel.Text + "'";
However, PLEASE read about SQL INJECTION. It is a very bad security issue and this is a perfect example.

C# SQLite database locked

I've tried all the solutions I could find to this problem, but for some reason I still get an exception stating the database I'm using is locked.
My code is as follows:
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
using (SQLiteConnection OriginatorDBConnection = new SQLiteConnection(connectionString))
{
string originatorName, originatorOrganisation, originatorAddress, originatorCellNumber, originatorTelNumber, originatorEmail;
originatorName = originatorNameTextBox.Text;
originatorOrganisation = originatorOrganisationTextBox.Text;
originatorAddress = originatorAddressRichTextBox.Text;
originatorCellNumber = originatorCellTextBox.Text;
originatorTelNumber = originatorTelTextBox.Text;
originatorEmail = originatorEmailTextBox.Text;
OriginatorDBConnection.Open();
string originatorINSERT = "INSERT INTO Originator (Name, Organisation, Address, CellphoneNumber, TelephoneNumber, Email) VALUES ('" + originatorName + "', '" + originatorOrganisation + "', '" + originatorAddress + "', '" + originatorCellNumber + "', '" + originatorTelNumber + "', '" + originatorEmail + "');";
using (SQLiteCommand originatorCommand = new SQLiteCommand(originatorINSERT, OriginatorDBConnection))
{
originatorCommand.ExecuteNonQuery();
}
OriginatorDBConnection.Close();
}
The closest solution on here that I could find to the problem was here: SQLite Database Locked exception
It didn't seem to work on my problem, however.
What am I doing wrong?
I have an additional function wherein I use the connection:
public AdminForm()
{
//Initialise AdminForm components.
InitializeComponent();
//Establish and open connection to ObservationDB.
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
ObservationDBConnection = new SQLiteConnection(connectionString);
ObservationDBConnection.Open();
//Query database to find all originators
string originatorSELECT = "SELECT * FROM Originator;";
string ECPNumberSELECT = "SELECT * FROM ECP";
SQLiteCommand command = new SQLiteCommand(originatorSELECT, ObservationDBConnection);
SQLiteDataReader reader = command.ExecuteReader();
SQLiteCommand command2 = new SQLiteCommand(ECPNumberSELECT, ObservationDBConnection);
SQLiteDataReader reader2 = command2.ExecuteReader();
//Populate OriginatorName combobox with names of existing originators.
List<string> originatorNames = new List<string>();
while (reader.Read())
{
originatorNames.Add(Convert.ToString(reader["Name"]));
}
OriginatorNameComboBox.DataSource = originatorNames;
//Populate ECP combobox with numbers of existing ECP.
List<string> ECPNumbers = new List<string>();
while (reader2.Read())
{
ECPNumbers.Add(Convert.ToString(reader2["Number"]));
}
ECPNumComboBox.DataSource = ECPNumbers;
//Populate TC Decision combobox with options.
List<string> TCDecision = new List<string>();
TCDecision.Add("Rework");
TCDecision.Add("Reject");
TCDecision.Add("Approve");
TCDecisionComboBox.DataSource = TCDecision;
ObservationDBConnection.Close();
}
And here:
private void SaveButton_Click(object sender, EventArgs e)
{
ObservationDBConnection.Open();
...
string ImpactTypeINSERT = "INSERT INTO ImpactType (ImpactType, Description) VALUES ('" + impactType + "', '" + impactDescription + "');";
SQLiteCommand ImpactTypeCommand = new SQLiteCommand(ImpactTypeINSERT, ObservationDBConnection);
//SQLiteDataReader ImpactTypeReader = ImpactTypeCommand.ExecuteReader();
ImpactTypeCommand.ExecuteNonQuery();
...
string TCDecisionINSERT = "INSERT INTO TCDecision (Decision, Description) VALUES ('" + TechnicalCommitteeDecision + "', '" + TechnicalCommitteeDescription + "');";
SQLiteCommand TCDecisionCommand = new SQLiteCommand(TCDecisionINSERT, ObservationDBConnection);
SQLiteDataReader TCDecisionReader = ImpactTypeCommand.ExecuteReader();
TCDecisionCommand.ExecuteNonQuery();
...
string OperationalDecisionINSERT = "INSERT INTO OperationalDecision (Decision, Description) VALUES ('" + operationalDecision + "', '" + operationalDescription + "');";
SQLiteCommand OperationalDecisionCommand = new SQLiteCommand(OperationalDecisionINSERT, ObservationDBConnection);
//SQLiteDataReader OperationalDecisionReader = OperationalDecisionCommand.ExecuteReader();
OperationalDecisionCommand.ExecuteNonQuery();
...
...
string OriginatorIDSELECT = "SELECT * FROM Originator WHERE Name='" + OriginatorNameComboBox.Text + "';";
SQLiteCommand OriginatorIDCommand = new SQLiteCommand(OriginatorIDSELECT, ObservationDBConnection);
SQLiteDataReader OriginatorIDReader = OriginatorIDCommand.ExecuteReader();
originatorIDOBS = OriginatorIDReader.GetOrdinal("ID");
//ImpactType
string impactTypeSELECT = "SELECT * FROM ImpactType WHERE ImpactType='" + impactType + "';";
SQLiteCommand impactTypeOBSCommand = new SQLiteCommand(impactTypeSELECT, ObservationDBConnection);
SQLiteDataReader impactTypeOBSReader = impactTypeOBSCommand.ExecuteReader();
impactTypeOBS = impactTypeOBSReader.GetOrdinal("ID");
string operationalDecisionOBSSELECT = "SELECT * FROM OperationalDecision WHERE Decision='" + operationalDecision + "';";
SQLiteCommand operationalDecisionOBSCommand = new SQLiteCommand(operationalDecisionOBSSELECT, ObservationDBConnection);
SQLiteDataReader operationalDecisionOBSReader = operationalDecisionOBSCommand.ExecuteReader();
operationalDecisionOBS = operationalDecisionOBSReader.GetOrdinal("ID");
...
string ECPOBSSELECT = "SELECT * FROM ECP WHERE Number='" + ECPNumComboBox.Text + "';";
SQLiteCommand ECPCommand = new SQLiteCommand(ECPOBSSELECT, ObservationDBConnection);
SQLiteDataReader ECPReader = ECPCommand.ExecuteReader();
ECPOBS = ECPReader.GetOrdinal("ID");
string CNISObservationINSERT = "INSERT INTO CNISObservation (Title, ReceiveDate, TableDate, OriginatorID, OriginatorReference, OriginatorDate, ObservationNumber, RevisionNumber, Description, Status, ImpactDescription, ImpactType, OperationalRequirementDescription, OperationalImpact, OperationalDecision, ProposedAction, TCDecision, ECP, SolutionOperationalImpact, TechnicalSolutionImpact) VALUES ('" +
titleOBS + "','"
+ receiveDateOBS + "','"
+ tableDateOBS + "','"
+ originatorIDOBS + ",'"
+ originatorReferenceOBS +"','"
+ originatorDateOBS + "','"
+ observationNumberOBS + "',"
+ revisionNumberOBS + ",'"
+ descriptionOBS + "',"
+ statusOBS + ",'"
+ impactDescriptionOBS + "',"
+ impactTypeOBS + ",'"
+ operationalRequirementDescriptionOBS + "','"
+ operationalImpactOBS + "',"
+ operationalDecisionOBS + ",'"
+ TCDecisionOBS + ","
+ ECPOBS + ",'"
+ solutionOperationalImpactOBS + "','"
+ technicalSolutionImpactOBS + "');";
...
string obsOBSSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationIDCommand = new SQLiteCommand(obsOBSSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationIDReader = CNISObservationIDCommand.ExecuteReader();
observationID = CNISObservationIDReader.GetOrdinal("ID");
...
foreach (var capabilityID in capabilitiesSelected)
{
string ObservationOperationalCapabilitiesINSERT = "INSERT INTO ObservationOperationalCapabilities (CapabilityID, ObservationID) VALUES (" + capabilityID + "," + observationID + ");";
SQLiteCommand ObservationOperationalCapabilitiesCommand = new SQLiteCommand(ObservationOperationalCapabilitiesINSERT, ObservationDBConnection);
// SQLiteDataReader ObservationOperationalCapabilitiesReader = ObservationOperationalCapabilitiesCommand.ExecuteReader();
ObservationOperationalCapabilitiesCommand.ExecuteNonQuery();
}
...
string CNISObservationIDSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationCommand = new SQLiteCommand(CNISObservationIDSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationReader = CNISObservationCommand.ExecuteReader();
CNISObservationID = CNISObservationReader.GetOrdinal("ID");
string CNISReleaseINSERT = "INSERT INTO CNISSection VALUES (" + CNISObservationID + "," + CNISRelease + "," + chapter + ",'" + paragraph + "','" + section + "','" + page +"');";
SQLiteCommand CNISReleaseCommand = new SQLiteCommand(CNISReleaseINSERT, ObservationDBConnection);
//SQLiteDataReader CNISReleaseReader = CNISReleaseCommand.ExecuteReader();
CNISReleaseCommand.ExecuteNonQuery();
ObservationDBConnection.Close();
}
I know I'm a lot late to the game, but it looks like you're not closing you reader variables in AdminForm() constructor. Consider wrapping the DataReaders in a using().
Wrapping around Command and Reader did work for me:
using (SqliteCommand cmd = new SqliteCommand(sQuery, m_Conn))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret_type = reader.GetInt32(0);
}
}
}
Please be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception

C# - Update SQL Table

I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is.
I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I hope someone can help me find my mistake.
EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.
As Michał Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:
var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = #LastName, FirstName = #FirstName, Title = #Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("#Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}
Few issues with your code:
1) Use using, when working with IDisposable objects, in your case connection and command.
2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")
3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Don't forget to execute the command
Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update CarTb1 set ( #RegNo , #MOdel , #Price , #Available where #Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("#RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("#Brand", combBrand.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#Color", txtColor.Text);
cmd.Parameters.AddWithValue("#Available", combAvailable.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();
Please use the ExecuteNonQuery() instead of SqlDataAdapter:
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");

SQL Query Command not working but does not give error SQL Server

I am developing a database application in C#.NET and SQL Server 2012.
Some of my SQL statements are not working properly . When I execute the code it does not give any error. But when I try to delete something or Update a record, I does not do that. The code lies below:
public void updateFinalTable()
{
DialogResult result = MessageBox.Show("Please make sure no fields are empty or they will get changed. \n\t\t Do you want to continue?",
"Important Note",
MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" + textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" + txtCredit.Text + "', Balance='" + txtBalance.Text + "' WHERE Id LIKE '" + textBox4.Text + "' ", con);
cmd.ExecuteNonQuery();
this.fianlTableBindingSource.AddNew();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select * from fianlTable WHERE (UserName LIKE '" + LoginSession.UserID + "')", con);
sda.Fill(dt);
dataGridView1.DataSource = dt;
refresh();
con.Close();
MessageBox.Show("Record Updated Successfully!");
catch (Exception)
{
MessageBox.Show("Record Could Not be updated...! ");
}
}
}
Similar is the case with delete operation . Both codes give no error but inside the database no change is observed.
You have used Like in your where condition instead of =. So your code should be like this -
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" +
dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" +
textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" +
txtCredit.Text + "', Balance='" + txtBalance.Text +
"' WHERE Id = '" + textBox4.Text + "' ", con);
ATTENTION This type of query potentially lead to SQL Injection. You better go with parametrized queries, like this -
string qry = = "UPDATE fianlTable SET AccountNumber = #accnt, CustomerName = #cname Where ID = #id)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#accnt", textBox1.Text);
cmd.Parameters.AddWithValue("#cname", textBox3.Text);
cmd.Parameters.AddWithValue("#id", textBox4.Text);
cmd.ExecuteNonQuery();

inserting or updating values into null textboxes

public void Updatecottonpurchase(int slipno, int basicprice, int premium, int totalamountpaid, int weight, int totalamountbasic, int totalamountpremium, int yeildestimates, int farmercode)
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
try
{
string sqlQuery = "UPDATE cottonpurchse SET slipno = '" + slipno + "' , basic price = '" + basicprice + "' , premium = '" + premium + "' , totalamountpaid = '" + totalamountpaid + "' , weight = '" + weight + "' , totalamountbasic = '" + totalamountbasic + "' , totalamountpremium = '" + totalamountpremium + "' , yeildestimated = '" + yeildestimates + "' WHERE farmercode = '" + farmercode + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sqlConn.Close();
}
finally
{
sqlConn.Close();
}
}
this is what ive done now yet nothing happens! i want to beable to update the null values but nothing happens! please help
This SQL code:
UPDATE TABLE cottonpurchase SET slipno= WHERE farmercode=
Does nothing, you need to add parameters,
see: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
You need to change the code into:
....
string queryString =
"UPDATE TABLE cottonpurchase SET slipno=#slipno WHERE farmercode=#farmercode";
try
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#slipno";
param.Value = inputfromsomewhere;
SqlParameter param = new SqlParameter();
param.ParameterName = "#farmercode";
param.Value = inputfromsomewhereelse;
//add new parameter to command object
command.Parameters.Add(param);
int result = command.ExecuteNonQuery();
//if result = 1 the update is performed
}
......
You need to add or choose a column for use as the primary key. The primary key should uniquely identify a row, and is used to locate the row to update.

Categories

Resources