update data in access database using name two column - c#

update data in access database using name two column
because one column have same data because SerialNumber and Start can be Repeat
that's make update in all row have same data
i use this code but i have syntax Error
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Timer set Stop='" + label1.Text + "'where (SerialNumber,Start)='" + comboBox1.Text + "','" + textBox1.Text + "' ";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Data saved");
connection.Close();
send_data f2 = new send_data(comboBox1.Text,label2.Text);
f2.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("ERORR" + ex);
}
}

The correct syntax for the WHERE clause is
WHERE fieldname operator value AND/OR fieldname operator value ....
So the correct way to update that record is
string query = #"update Timer set Stop=? where SerialNumber = ? AND Start = ?";
command.CommandText = query;
command.Parameters.AddWithValue("#p1", label1.Text);
command.Parameters.AddWithValue("#p2", comboBox1.Text );
command.Parameters.AddWithValue("#p3", textBox1.Text);
command.ExecuteNonQuery();
Notice that before the WHERE keyword you need a space and I have changed your code to use a more secure parameterized approach instead of string concatenation

Related

Invalid object name 'Main' error when inserting into Database - C# (WebForms), MySql

I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.

Invalid attempt to call read when reader is closed when inserting data

i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.

How to put the autoincrement value in textbox

private void button1_Click(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= system; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
sqlconn.Open();
sqlcomm.CommandType = CommandType.Text;
sqlcomm.Connection = sqlconn;
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "')";
sqlcomm.ExecuteNonQuery();
sqlconn.Close();
MessageBox.Show("Record saved");
}
This is a code in the add button. In phpmyadmin, I checked the autoincrement box. Whenever I run the form, I left the textBox1 which is the ID empty and I input a name in textBox2 which is the Lastname. In phpmyadmin, the ID autoincrements. The textbox1 should have a value of 0001 before I click the add button then after I click the add button, the textBox1 should have 0002. How do I put the autoincrement value in textBox1?This is in winform c#. Sorry for the bad english TIA.
If your database has an ID column with AUTO_INCREMENT set, you do not need to pass a value for the ID into the SQL Insert Statement. You can simply do:
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + ')";
It is also better to use SqlCommand instead of string concatenation as it is protects against SQL Injection and also deals with Type and formatting issues.
That's the query you need to run together with the insert.
SELECT LAST_INSERT_ID();
Here's some code to get the ID, first declare a global String somewhere in the class like that
private String entryIdString;
then
public int insertGetEntryID()
{
String sqlquery = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "'); SELECT LAST_INSERT_ID();";
SqlCommand command = new SqlCommand(sqlquery, sqlconn);
try
{
sqlconn.Open();
entryIdStr = command.ExecuteScalar().ToString();
return int.Parse(entryIdStr);
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
return -1;
}
finally
{
sqlconn.Close();
}
}
This method returns an integer holding the last ID in your table. Now you just set the value to textBox1
textBox1.Text = "ID: " + getEntryID();
or if you want just the ID
textBox1.Text = "" + getEntryID();
I was also just about to tell you what Gideon said about you inserting an ID (when if it's set to autoincrement in the DB, you don't need to).

update data using oledb in c#

I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}

C# Sql Column name is not valid

private void button4_Click_1(object sender, EventArgs e)
{
string s = textBox1.Text;
string s1 = comboBox1.Text;
string s2 = comboBox2.Text;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=D:\Desktop\DB2\DB2\Database1.sdf");
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas=[s] Where [Kambario rūšis]=[s1] ", conn);
cmd.ExecuteNonQuery();
toolStripStatusLabel1.Text = "Duomenys įrašyti";
conn.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
I am trying to update my datatable by updating Klientas value with textbox1.Text which is made to string = s. It should work fine as Sql But I get an error saying that The column name is not valid Column = s1. s1 shouldn't be targeted as column name it should be used as column row value.
This is outdated image Kliento ID is changed to Klientas
Try this:
SqlCeCommand cmd = new SqlCeCommand("update Kambariai set Klientas="+s+" Where [Kambario rūšis]='"+s1+"' ", conn);
Analysis:
From what you have tried, cmd has value like :
update Kambariai set Klientas=s Where [Kambario rūšis]=s1
From by putting proper double and single quotes around it, the value would be like:
update Kambariai set Klientas=1 Where [Kambario rūšis]='bar'
Side Note:
I would not recommend this method since it increases the risk of SQL injection. Use parameterized query instead.
Try This :
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas='" + s +"' Where [Kambario rūšis]='" + s1 + "'", conn);

Categories