MS Access Update Query Not Working - c#

I can't Figure out what is wrong with the query, but it is not updating any value in the Table
string qry = "UPDATE Stock SET Itemname=#n,Unit=#u,Price=#p,Tax=#t,Balance=#b,Status=#s Where Sid=#sid";
OleDbCommand ocmd = new OleDbCommand(qry,BBC);
ocmd.Parameters.AddWithValue("#n", name);
ocmd.Parameters.AddWithValue("#u", unit);
ocmd.Parameters.AddWithValue("#p", price);
ocmd.Parameters.AddWithValue("#t", tax);
ocmd.Parameters.AddWithValue("#b", balance);
ocmd.Parameters.AddWithValue("#s", status);
ocmd.Parameters.AddWithValue("#sid", sid);
ocmd.ExecuteNonQuery();
Price,Tax and Balance are Decimal values.
I did debug and its working fine but just not updating the value.

set the type of each parameter and execute the query.
List<OleDbParameter> paramList = new List<OleDbParameter>();
OleDbParameter param = new OleDbParameter("#param", OleDbType.TypeName);
param.Value = value;
paramList.Add(param);
ocmd.Parameters.AddRange(paramArray);

I think this will do it for you.
string ConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\your_path_here\test.accdb";
using(OleDbConnection conn = new OleDbConnection(ConnString ))
using(OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = # "UPDATE Stock SET Itemname=#n,Unit=#u,Price=#p,Tax=#t,Balance=#b,Status=#s Where Sid=#sid";
cmd.Parameters.AddWithValue("#n", txtItemName.Text);
cmd.Parameters.AddWithValue("#u", txtUnit.Text);
cmd.Parameters.AddWithValue("#p", Convert.ToDecimal(txtPrice.Text));
cmd.Parameters.AddWithValue("#t", Convert.ToDecimal(txtTax.Text));
cmd.Parameters.AddWithValue("#b", Convert.ToDecimal(txtBalance.Text));
cmd.Parameters.AddWithValue("#s", txtStatus.Text);
cmd.Parameters.AddWithValue("#sid", txtSID.Text);
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}

Related

Issue in update statement

I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}

c# database Select then insert. But the value is 0

I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}

How to Save 2 different Cell values into 2 different variables from database C#

I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}

"executenonquery connection property has not been initialized"

SqlConnection cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
The error message
Executenonquery connection property has not been initialized.
the problem with your current code is that you have not set the Connection property of the SqlCommand object. Try this,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
and you must also parameterized the values set on the name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name=#name";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
FULL CODE
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = #"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = #"UPDATE navaznost_ukolu
SET finish = #finish
WHERE Name = #Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for propr object disposal
use try-catch block to properly handle objects
The error is self-explanatory, you have not assigned the connection to the command. You can use the constructor:
using(var cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=#finish where Name=#Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("#finish", finish);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
Note that i've also used a sql-parameter for the Name and using statements to ensure that anything implementing IDisposable gets disposed, even in case of an exception. This will also close the connection.

return student information - SQL/C# assignment

so essentially, I have two text fields, one with the firstName and one with the lastName of the student. What I want the program to do is this:
return the student's phone number and comments using the firstName and lastName from the TextBox above. This is what I have so far:
if (actionButton.Text == "Update")
{
SqlConnection cn;
cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE #firstName AND lastName LIKE #lastName"; //AND lastName LIKE #lastName"
//used this part to delete records
SqlParameter param = new SqlParameter();
param.ParameterName = "#firstName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = firstNameTB.Text;
cmd.Parameters.Add(param);
param.ParameterName = "#lastName";
param.Direction = ParameterDirection.Input;
param.SqlDbType = SqlDbType.VarChar;
param.Value = lastNameTB.Text;
cmd.Parameters.Add(param);
//display data in a listbox
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
string s;
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cmd.ExecuteNonQuery();
cn.Close();
}
I'm not sure where to go from here. In the code I have placed two comment statements, so I have used the above in two different parts of my assignment, but when I bring them together, it doesn't work.
what is happening is that I am not getting any results. Essentially I need it to give me the phone number and comments of the student indicated in the two text boxes
I assume you're getting an error, yes? You are trying to do two operations on the same command object and my hazy recollection says that's not going to work. Try removing this line.
cmd.ExecuteNonQuery();
If you have studied the using statement, that's typically a better solution for handling resources like your connection and reader.
if (actionButton.Text == "Update")
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
cn.Open();
MessageBox.Show(cn.ConnectionState.ToString());
// If you are shown "Open" by above messagebox and you are using correct table and column names then you will get accurate results by following code
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE '" + firstNameTB.Text + "' AND lastName LIKE '" + lastNameTB.Text + "' ";
SqlDataReader reader = cmd.ExecuteReader();
string s = "";
while (reader.Read())
{
s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
MessageBox.Show(s);
}
cn.Close();
}

Categories