Update in C# using Access database - c#

I've been trying to update in a DataGridView and it keeps returning this
No value given for one or more required parameters
Here's my code
private void btnAlterar_Click(object sender, EventArgs e)
{
try
{
string strincon = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\flavi\Desktop\Pet&Shop.2\PetShop\TelaAbertura\bin\Debug\DatabasePS.mdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection(strincon);
con.Open();
String comando = "UPDATE Funcionario SET Nome= '" + txtNome.Text + "' , Login= '" + txtLogin.Text + "' , Senha= '" + txtSenha.Text + "', Email= '" + txtEmail.Text + "' , Cargo= '" + txtCargo.Text + "' WHERE Codigo =" + codigo;
OleDbCommand cmd = new OleDbCommand(comando, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Dados Alterados Com Sucesso!");
txtCargo.Clear();
txtEmail.Clear();
txtLogin.Clear();
txtNome.Clear();
txtSenha.Clear();
con.Close();
}
catch (Exception erro)
{
MessageBox.Show(erro.Message);
}
}

You need to add brackets on field names because may be some field name is keyword on Access. Change your query as follow:
String comando = "UPDATE [Funcionario] SET [Nome]= '" + txtNome.Text + "' , [Login]= '" + txtLogin.Text + "' , [Senha]= '" + txtSenha.Text + "', [Email]= '" + txtEmail.Text + "' , [Cargo]= '" + txtCargo.Text + "' WHERE [Codigo] =" + codigo;

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.

Cannot insert duplicate value into datatable when updating record from textbox

Trying to update records in my datatable using textboxes on a button click. The error message says is cannot insert a duplicate value, and shows the value that I have entered into txtID. This is the code for the update button:
private void btnUpdate_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand command = new SqlCommand();
String query = "UPDATE Bug SET Tester_ID=" + txtID.Text + "',Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "')";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
adapter.SelectCommand.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Updated Successfully");
}
You do not have where clause in that query, so it is updating all records in the table, which is making some records duplicate. Hence the error.
The could be due to your defined table structure.
P.S. You should look for SQL injection attack and should parameterize your query to avoid it.
Edit based on your comment
String query = "UPDATE Bug Set Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "' WHERE Tester_ID='" + txtID.Text + "'";
If Tester_Id is numeric, you don't need those quotes.
Where clause comes after Set.
Here is the Parameterized version:
String query = "UPDATE Bug Set Tester_Name=#Tester_Name,Application_Name= #AppName,Class_Name= #Class_Name,Line_No= #Line_No,Error_Description= #Error_Description,Source_Code= #Source_Code,Status= #Status WHERE Tester_ID=#Tester_ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#Tester_Name", "XYZ");
// other params
command.Parameters.AddWithValue("#Tester_ID", 10);

Insert checkbox value into database SQL

I want to insert the value of a checkbox into the database.
But in the database the column is null.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NAWAF;Initial Catalog=waterreport;Integrated Security=True");
con.Open();
if (checkBox1.CheckState == CheckState.Checked)
{
string chkek = "finish";
}
SqlCommand tump;
SqlCommand orugg;
string tmp = " UPDATE reportonetmp set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "' WHERE no like '" + label13.Text + "'";
tump = new SqlCommand(tmp, con);
tump.ExecuteNonQuery();
string org = " UPDATE reportone set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "',checkk ='" + chkek + "' WHERE no like '" + label13.Text + "'";
orugg = new SqlCommand(org, con);
orugg.ExecuteNonQuery();
con.Close();
}
Aside from other problems (like having non-parametrised queries), are you sure that your DB column is called 'checkk'?
If that's correct, I would convert that DB column into a bit one (if you're using SQL Server) or boolean and updating it like this, instead of using an string variable:
"',checkk ='" + checkBox1.Checked
put oncheckchanged on checkbox control in aspx page and if checked means set values to 1 else 0(put if condition in checkedchanged event, so simple).same way you can get from database if value 1 means checkbox ID.Checked like this enough

How to save a picture to an access database table?

I am using this code to save a picture into an access database table:
byte[] fromPath = File.ReadAllBytes(Picture_Path);
byte[] fromPath2 = File.ReadAllBytes(BacksidePicture_Path);
con.Open();
string query = "Insert Into DML_Books_List (" +
"ID,ISNBORCode, Title, Donor, DocType, Edition, Author1, Author2, Author3, " +
"Author4, Translator, Publisher, Subject, USubject, Shelf, Cost, " +
"Language, Pages, Image, BImage, Description, Date) VALUES ('" +
"2" + "','" + ISNB_AddBook_Books_TXT.Text + "', '" +
Title_AddBook_Books_TXT.Text +
"', '" + Donor_AddBook_Books_TXT.Text + "', '" +
DocType_AddBook_Books_CBE.SelectedItem + "', '" +
Edition_AddBook_Books_TXT.Text + "', '" +
Author1_AddBook_Books_TXT.Text + "', '" +
Author2_AddBook_Books_TXT.Text + "', '" +
Author3_AddBook_Books_TXT.Text + "', '" +
Author4_AddBook_Books_TXT.Text + "', '" +
Translator_AddBook_Books_TXT.Text + "', '" +
Publisher_AddBook_Books_CBE.SelectedItem + "', '" +
Subject_AddBook_Books_CBE.SelectedItem + "', '" +
USubject_AddBook_Books_CBE.SelectedItem + "', '" +
Shelf_AddBook_Books_CBE.SelectedItem + "', '" +
Cost_AddBook_Books_TXT.Text + "', '" +
Language_AddBook_Books_CBE.SelectedItem + "', '" +
Pages_AddBook_Books_TXT.Text + "', '" +
#fromPath + "', '" + #fromPath2 + "', '" +
Description_AddBook_Books_MemoEdit.Text + "', '" +
Date_AddBook_Books_TXT.Text + "')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
con.Close();
But it has some problems.
Please Help Me solve this problem.
Thank you
OleDb.OleDbConnection cn = new OleDb.OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "\\data.mdb";
cn.Open();
byte[] arrImage = null;
string strImage = null;
IO.MemoryStream myMs = new IO.MemoryStream();
//
if ((this.picPhoto.Image != null)) {
this.picPhoto.Image.Save(myMs, this.picPhoto.Image.RawFormat);
arrImage = myMs.GetBuffer;
strImage = "?";
} else {
arrImage = null;
strImage = "NULL";
}
OleDb.OleDbCommand myCmd = new OleDb.OleDbCommand();
myCmd.Connection = cn;
myCmd.CommandText = "INSERT INTO tblstudent(stdid, [name], photo) " + " VALUES(" + this.txtID.Text + ",'" + this.txtName.Text + "'," + strImage + ")";
if (strImage == "?") {
myCmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage;
}
Interaction.MsgBox("Data save successfully!");
myCmd.ExecuteNonQuery();
cn.Close();
Source
use parameters like below code:
Assume you have two columns in your table called ID and Image. Now you going to insert data using SQL parameters
you need SQL statement like
Insert Into DML_Books_List(ID, [Image]) values (#id, #image)
#id and #image are the given names for parameters. You can set the parameter values by parameter name.
var pic = File.ReadAllBytes(yourFileName);
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("Insert Into DML_Books_List(ID, [Image]) values (#id, #image)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", pic);
cmd.ExecuteNonQuery();
}
Use parametrized query..
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database");
OleDbCommand command = connection.CreateCommand();
imageData = ReadByteArrayFromFile(#"c:\test.jpg");
command.CommandText = "Insert into SomeTable (Name, ImageData) VALUES (#Name, #Img)"
command.Parameters.AddWithValue("#Name", "theName");
command.Parameters.AddWithValue("#Img", imageData);
command.ExecuteNonQuery();

Updating Database

So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();
You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";
Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.
Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.
In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.

Categories

Resources