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;
Related
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;
}
}
I have an update panel with some gridviews being populated on postback as well as some textboxes that are populated through code and an SqlDataReader on _SelectedIndexChanged. Everything is working except for the two date textboxes that are set to TextMode=Date are not populating. I'm sure it's some formatting issue and I've searched and tried a few different things to no avail..... Thanks in advance !
P.s. edited out connection string
public void ddlSO_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = "";
String strQuery = "select strServiceOrderNo, strCustomerNo, strCustomerName, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, strServiceRequestDate, strServiceOrderDate, intStatusCodeID, intRepID from TServiceOrders where" +
" intServiceOrderID = #intServiceOrderID";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#intServiceOrderID", ddlSO.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtCUSTNO.Text = sdr["strCustomerNo"].ToString();
txtSONO.Text = sdr["strServiceOrderNo"].ToString();
txtAddress1.Text = sdr["strCustomerAddress1"].ToString();
txtAddress2.Text = sdr["strCustomerAddress2"].ToString();
txtAddress3.Text = sdr["strCustomerAddress3"].ToString();
txtDateCreated.Text = sdr["strServiceOrderDate"].ToString() ;
txtDateDue.Text = sdr["strServiceRequestDate"].ToString();
txtCustName.Text = sdr["strCustomerName"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
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.
I need Insert data in Datagridview to Database in Sql Server 2008. But don't work.
".Rows(i)" Message Error:
'Non-invocable member 'System.Windows.Forms.DataGridView.Rows' cannot
be used like a method.'
Code C# (Windows Form)
SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;
private void testExcel_Load(object sender, EventArgs e)
{
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button2_Click(object sender, EventArgs e)
{
tr = Conn.BeginTransaction();
sb.Remove(0, sb.Length);
sb.Append("INSERT INTO tableAset (Id,AsId,AsRefid,Invid,TypeName)");
sb.Append("VALUES (#Id,#AsId,#AsRefid,#Invid,#TypeName)");
string sqlSave = sb.ToString();
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
cmd.CommandText = sqlSave;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.Transaction = tr;
cmd.Parameters.Clear();
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = dataGridView1.Rows(i).Cells(0).Value;
cmd.Parameters.Add("#AsId", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(1).Value;
cmd.Parameters.Add("#AsRefid", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(2).Value;
cmd.Parameters.Add("#Invid", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(3).Value;
cmd.Parameters.Add("#TypeName", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(4).Value;
cmd.ExecuteNonQuery();
tr.Commit();
MessageBox.Show("It's Done!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
Thank you very much for your time. :)
You should use rows[i] instead, the same goes for the Cells:
dataGridView1.Rows[i].Cells[0].Value
Take a look at the Rows property
just replace the round brackets with the square one
dataGridView1.Rows[i].Cells[0].Value;
I recommend to use SqlBulkCopy.You can easily get the GridView data in DataTable format and you can pass the DataTable to SqlBulkCopy WriteToServer
You can check this example.
https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-insert-bulk-data-from-GridView-to-database-in-ASPNet.aspx
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";