Updating records - c#

private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True"))
{
string sqlQuery = #"UPDATE cottonpurchase SET #slipNo, #basicprice, #weight, #totalamountbasic, #premium, #totalamountpremium, #totalamountpaid, #yeildestimates WHERE farmercode = #farmercode";
{
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
cmd.Parameters.Add("#slipNo", SqlDbType.Int).Value = TxtSlipNo.Text;
cmd.Parameters.Add("#basicprice", SqlDbType.Int).Value = TxtBasicPrice.Text;
cmd.Parameters.Add("#weight", SqlDbType.Int).Value = TxtWeight.Text;
cmd.Parameters.Add("#totalamountbasic", SqlDbType.Int).Value = TxtTotalAmountBasic.Text;
cmd.Parameters.Add("#premium", SqlDbType.Int).Value = TxtPremium.Text;
cmd.Parameters.Add("#totalamountpremium", SqlDbType.Int).Value = TxtTotalAmountPremium.Text;
cmd.Parameters.Add("#totalamountpaid", SqlDbType.Int).Value = TxtTotalAmountPaid.Text;
cmd.Parameters.Add("#yeildestimates", SqlDbType.Int).Value = TxtYeildEstimates.Text;
sqlConn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
It's giving me an error even though everything seems fine with my code:
error : incorrect syntax near ','

You need to specify column names that you are trying to set.
string sqlQuery = #"
UPDATE cottonpurchase
SET
slipNo = #slipNo,
basicprice= #basicprice,
weight = #weight,
totalamountbasic = #totalamountbasic,
premium = #premium,
totalamountpremium = #totalamountpremium,
totalamountpaid = #totalamountpaid,
yeildestimates = #yeildestimates
WHERE farmercode = #farmercode";
Also, you didn't provide #farmercode parameter:
cmd.Parameters.AddWithValue("#farmercode", <someValue>);

You forgot to mention the column names in the set.
string sqlQuery = #"UPDATE cottonpurchase SET slipNo=#slipNo, basicprice=#basicprice, ... WHERE farmercode = #farmercode";

Related

ExecuteNonQuery doesn't update my table while I am using bind variables

I am using this code in c# to update my table:
public static int updateMytable(string accessCode, string response)
{
OracleConnection conn = DB.GetConnection();
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "update mytable set response_id= :p_response , response_date=sysdate where access_code = :p_access_code";
cmd.Parameters.Add("p_access_code", accessCode);
cmd.Parameters.Add("p_response", response);
cmd.CommandType = CommandType.Text;
int res = cmd.ExecuteNonQuery();
conn.Close();
return res;
}
access_code is varchar2
When I remove the condition "where" It updates everything.
When I use a string command instead of bind variables it works fine too.
string str = "update mytable set response_id= "+response+" , response_date=sysdate where access_code = "+accessCode;
Could you advise?
Add cmd.BindByName = true; in order to bind variables (:p_response, :p_access_code) by their names, not positions:
public static int updateMytable(string accessCode, string response) {
if (string.IsNullOrEmpty(accessCode))
return 0;
using (OracleConnection conn = DB.GetConnection()) {
conn.Open();
using (OracleCommand cmd = new OracleCommand()) {
// When binding varaibles, use their names, not positions
cmd.BindByName = true;
cmd.Connection = conn;
cmd.CommandText =
#"update mytable
set response_id = :p_response,
response_date = sysdate
where access_code = :p_access_code";
cmd.Parameters.Add(":p_response", OracleDbType.Varchar2);
cmd.Parameters.Add(":p_access_code", OracleDbType.Varchar2);
cmd.Parameters[":p_response"].Value = string.IsNullOrEmpty(response)
? (object) (DBNull.Value)
: response;
cmd.Parameters[":p_access_code"].Value = accessCode;
return cmd.ExecuteNonQuery();
}
}
}

SQL command returning null for value

I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}

Why can't I get the current ID and place in another table?

I am attempting to create a simple news and image system, I first need to use SCOPE_IDENTITY() and execute scalar, but I'm not having much luck. I get a:
The name 'newID' does not exist in the current context
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("/images/admin/news/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int newID = 0;
string strQuery = #"insert into tblFiles (FileName, FilePath) values(#FileName, #FilePath); select cast(scope_identity() As int);";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
}
if (newID > 0)
{
string strAddNewsQuery = #"insert into tblNews (newsTitle, newsDate, newsSummary, newsContent, newsPicID)
values(#newsTitle, #newsDate, #newsSummary, #newsContent, #newsPicID)";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
command.Parameters.AddWithValue("#newsDate", txtnewsdate.Text);
command.Parameters.AddWithValue("#newsSummary", txtnewssummary.Text);
command.Parameters.AddWithValue("#newsContent", txtnewsmaincontent.Text);
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally {
connection.Close();
connection.Dispose();
}
}
}
}
}
An int does not have properties you can access. Change
command.Parameters.AddWithValue("#newsPicID", newID.Value);
into
command.Parameters.AddWithValue("#newsPicID", newID);
Even better is to use parameters with the database value type specified.
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
But you are trying to get the SCOPE_IDENTITY() of table tblNews, not from tblFiles to be used in tblNews as newsPicID. You need to get SCOPE_IDENTITY() from the first database command.
UPDATE
And you need to assign the connection to the command.
SqlCommand cmd = new SqlCommand(strQuery, con)
UPDATE 2
Here is a complete snippet to get you started. Notice the wrapping with using. This ensures proper disposal of connections.
int newID = 0;
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
if (newID > 0)
{
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
//etc
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
}
}

ASP.Net C# - Setting a MySQL query and parameters based on a condition

How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

ExecutreNonQuery and Update Statement

Receiving this error when I try saving.
Incorrect Syntax near the word update.
Seems like an obvious fix but I can't seem to find it. Hoping fresh eyes will help! Thanks
protected void btnSave_Click(object sender, EventArgs e)
{
Button EditButton = (Button)EditLoginView.FindControl("EditButton");
Button SaveButton = (Button)EditLoginView.FindControl("SaveButton");
TitleLanguage.ActiveViewIndex = 0;
LanguageView.ActiveViewIndex = 0;
EditButton.Visible = true;
SaveButton.Visible = false;
//update the file in the database
string strQuery = "UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title, update=#update WHERE link_title = #link_title";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#en_title", SqlDbType.VarChar).Value = Edit_EnglishT.Text;
cmd.Parameters.Add("#fr_title", SqlDbType.VarChar).Value = Edit_FrenchT.Text;
cmd.Parameters.Add("#en_content", SqlDbType.VarChar).Value = Edit_English.Text;
cmd.Parameters.Add("#fr_content", SqlDbType.VarChar).Value = Edit_French.Text;
cmd.Parameters.Add("#update", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
UpdateData(cmd);
}
private Boolean UpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["randolphConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
UPDATE is a reserved keyword in T-SQL. You should use it with square brackets like [UPDATE]
Like;
string strQuery = #"UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title,
[update]=#update WHERE link_title = #link_title";
^^^^^^^^
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Also change your
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
to
cmd.Parameters.Add("#link_title", SqlDbType.VarChar).Value = linktitle;
Because you declared your parameter name as #link_title not #link_ in your strQuery.
EDIT: For clarification, you don't need to use a method (UpdateData) for that such a process. Just use like this;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["randolphConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(strConnString))
using(SqlCommand cmd = con.CreateCommand())
{
string strQuery = #"UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title, [update]=#update WHERE link_title = #link_title";
cmd.CommandText = strQuery;
cmd.Parameters...;
.....
.....
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
You define the field update which is a reserved keyword.
Try [update] instead like in this sample:
UPDATE pages
SET en_content = #en_Content
, fr_Content = #fr_content
, fr_Title=#fr_title
, en_Title=#en_title
, [update]=#update
WHERE link_title = #link_title
In your last parameter, you use #link_title
but in the Parameter.Add, you use:
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
Try to change for this one:
cmd.Parameters.Add("#link_title", SqlDbType.VarChar).Value = linktitle;

Categories

Resources