ERROR : The multi-part identifier could not be bound, c# console Application - c#

SqlConnection cn = new SqlConnection("user id=ID;" +
"password=PASS;server=svr;" +
"Trusted_Connection=no;" +
"database=db; " +
"connection timeout=30");
cn.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = cn;
Console.WriteLine(ListofOrders.Count);
for (int i = 0; i < ListofOrders.Count; i++)
command1.CommandText += string.Format("update table set Status='Expired' where GUID={0};", ListofOrders[i].ToString());
command1.ExecuteNonQuery();
// LogicHandler.UpdateActiveOrders();
Console.WriteLine("DONE", ConsoleColor.Cyan);
Getting error at this step: command1.ExecuteNonQuery(); Error Message: The multi-part identifier could not be bound.
What i am trying here is I am running a select query and getting that data into the ListofOrders list from that I wanna run the update to those data in the list.
Please help

If you use a Reserved Keyword like table you have to wrap it in square brackets: [table]. But it would be better to not use them in the first place.
I guess you need to wrap the Guid with apostrophes like in GUID='{0}'. Howver, you should use sql-parameters instead of string concatenation, always. That prevents also sql-injection.
string update = #"update tablename -- or [Table] but i wouldnt do that
set Status='Expired'
where GUID=#GUID";
command1.CommandText = update;
command1.Parameters.Add("#GUID", SqlDbType.UniqueIdentifier).Value = new Guid(ListofOrders[i].ToString());
As an aside, why have you used command1.CommandText += instead of just command1.CommandText =? That is at least confusing, if you reuse the command it could also cause errors.

Related

How to Update paragraph from mysql table using c#

I tried to update a paragraph from mysql table,but i got error like this
"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's first-ever super-villainess."
My mysql Query
cmd.CommandText = "UPDATE `moviemaster` SET `Runtime`='" + runtime + "',`DateMasterId`='" + dateid + "',`Trailer`='" + trailer + "',`Synopsis`='" + synopsis + "' WHERE `MovieMasterId`='" + movieid + "'";
I got error in 'synopsis',it's a big data containing a large paragraph.If i romove 'Synopsis' section from the query,everything working fine.What exactly the problem.How can i resolve this?
#SonerGönül:Ok,fine.. then please show me an example of parameterised
query
Sure. I also wanna add a few best practice as well.
Use using statement to dispose your connection and command automatically.
You don't need to escape every column with `` characters. You should only escape if they are reserved keywords for your db provider. Of course, at the end, changing them to non-reserved words is better.
Do not use AddWithValue method. It may generate upexpected and surprising result sometimes. Use Add method overload to specify your parameter type and it's size.
using (var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"UPDATE moviemaster
SET Runtime = #runtime, DateMasterId = #dateid, Trailer = #trailer, Synopsis = #synopsis
WHERE MovieMasterId = #movieid";
cmd.Parameters.Add("#runtime", MySqlDbType.VarChar).Value = runtime; ;
cmd.Parameters.Add("#dateid", MySqlDbType.VarChar).Value = dateid;
cmd.Parameters.Add("#trailer", MySqlDbType.VarChar).Value = trailer;
cmd.Parameters.Add("#synopsis", MySqlDbType.VarChar).Value = synopsis;
cmd.Parameters.Add("#movieid", MySqlDbType.VarChar).Value = movieid;
// I assumed your column types are VarChar.
con.Open();
cmd.ExecuteNonQuery();
}
Please avoid using inline query. Your database can be subjected to SQL Injection. See this example, on what can be done using SQL Injection.
And use paramterized query instead. Here is the example taken from here. This way, even if your string has special characters, it will not break and let you insert/update/select based on parameters.
private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = #param_val_1 AND VAL_2 = #param_val_2;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.AddWithValue("#param_val_1", val1);
m.Parameters.AddWithValue("#param_val_2", val2);
level = Convert.ToInt32(m.ExecuteScalar());
return true;
}
and finally, your query will become
cmd.CommandText = "UPDATE `moviemaster` SET `Runtime`= #param1,`DateMasterId`= #dateid, `Trailer`= #trailer,`Synopsis`= #synopsis WHERE `MovieMasterId`= #movieid";
cmd.Parameters.AddWithValue("#param1", runtime);
cmd.Parameters.AddWithValue("#dateid", dateid);
cmd.Parameters.AddWithValue("#trailer", trailer);
cmd.Parameters.AddWithValue("#synopsis", synopsis);
cmd.Parameters.AddWithValue("#movieid", movieid);

Syntax error in UPDATE statement OleDbException

I'm writing an application which stores user information. Currently the user is supposed to update their Name, Height, Weight and Birthday.
string height = TB_ClientHeight.Text;
string weight = TB_ClientWeight.Text;
string name = TB_ClientName.Text;
string bday = dateTimePicker1.Value.ToString("dd-MM-yyyy");
int heightint = Convert.ToInt32(height);
int weightint = Convert.ToInt32(weight);
It's updated by calling the public static string username variable from another form and using that as the WHERE UserName = #username.
usernamestringo = Login.usernameFromLogin;
I've followed other SO answers in this context and corrected some issues (like preventing SQL Injection). However I'm still getting a syntax error while updating these fields as claimed by OleDbException.
using (OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:\Repos\Database\Database.accdb;Persist Security Info=False"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
string query = "UPDATE TPersons SET Name=#Name, SET Height=#Height, SET Weight=#Weight, SET Bday=#Bday " + " WHERE FirstName= #username";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Name", name.ToString());
cmd.Parameters.AddWithValue("#Height", heightint.ToString());
cmd.Parameters.AddWithValue("#Weight", weightint.ToString());
cmd.Parameters.AddWithValue("#Bday", bday.ToString());
cmd.Parameters.AddWithValue("#username", usernamestringo);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Updated!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Parameters.Clear();
}
The OleDbException is:
Index #0
NativeError: -526847407
Source: Microsoft Access Database Engine
SQLState: 3000
Description (message): Syntax error in UPDATE statement.
Could anyone guide me where my syntax is wrong? Thank you!
The UPDATE syntax is
UPDATE <tablename> SET field1=Value1, field2=Value2 WHERE primarykeyname=Value3
The SET keyword precedes only the first column to update, and you have another problem with the NAME column. In Access this is a reserved keyword. Use brackets around that column name (or better change it to something not so troublesome)
So:
string query = #"UPDATE TPersons SET [Name]=#Name,
Height=#Height, Weight=#Weight, Bday=#Bday
WHERE FirstName= #username";
Not strictly related to your current problem, but you should look also at this article Can we stop using AddWithValue already? The DbCommand.AddWithValue is a shortcut with numerous drawbacks. Better avoid it.

How to initialize Access Number field in C-Sharp

I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements

Count from SQL Rows into C# textbox

Hi there its the first time to use stackoverflow so hi every one L)
i'm a beginner into C# forms i take it as a fun hobby.
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
Int32 count = (Int32)comm.ExecuteScalar();
textbox2.Text ="Found "+ count+" Members;
well its just a mix between 2 codes i have got from google xD
how ever the error appear here textbox2.Text ="Found "+ count+" Members;
There are a couple of things wrong with this line of code:
textbox2.Text ="Found "+ count+" Members;
First of all, there's a syntax error. You never close the second set of quotes. You'd do so like this:
textbox2.Text ="Found "+ count+" Members";
However, string concatenation like this is still a little messy. You have two literal strings and you're trying to add them to an integer, which isn't entirely intuitive (and probably slower than it needs to be). Instead, consider using a formatting string:
textbox2.Text = string.Format("Found {0} Members", count);
This will take the value from count (which is an integer) and, internally to the string.Format() function, discern its string representation and insert it into the placeholder in the formatted string.
UPDATE: That takes care of the compile-time errors. Now you're going to get a run-time error from this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
As soon as you try to execute that SQL statement you're going to get an error from the database because the resulting query has a syntax error:
SELECT COUNT(*) FROM Members where sponser = some text'
You're missing the opening single-quote for the parameter. Something like this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = '"
+textbox1.text+"'", connection);
However, and this is important, you're still not done. This line of code is wide open to a very common and easily exploitable vulnerability called SQL Injection. You'll want to move away from direct string concatenation and use parameters for your SQL queries. Something like this:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = #sponser");
cmd.Parameters.Add("#sponser", textbox1.text);
Int32 count = (Int32)comm.ExecuteScalar();
Know that there is still a lot more you can do to improve this, which is all worth learning over time. Things you can look into are:
Checking and validating user input (textbox1.text) before you even try to use it in a SQL query.
Checking the output of comm.ExecuteScalar() before trying to directly cast it to an Int32 (this would give you a runtime error if it returns anything other than an integer for some reason).
Consider using something like Linq to Sql in place of ADO.NET components as it does a lot more for you with less code on your part.
protected void Page_Load(object sender, EventArgs e)
{
lb1.Text = GetRecordCount(textbox2.Text).ToString();
}
private int GetRecordCount(string myParameter)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
Int32 count = 0;
string sql = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Sponsor", SqlDbType.VarChar);
cmd.Parameters["#Sponsor"].Value = myParameter;
try
{
conn.Open();
count = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
}
}
return (int)count;
}
You are missing a closing " at the end:
textbox2.Text ="Found "+ count+" Members";
You code is vulnerable to SQL Injections. Please consider using Parameters.
private int GetMemberCount(string connectionString, string sponsor)
{
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
command.Parameters.AddWithValue("#Sponsor", sponsor);
return Convert.ToInt32(command.ExecuteScalar());
}
}
//Usage
var sponsor = textbox1.text;
var count = GetMemberCount(connectionString, sponsor);
textbox2.Text = string.Format("Found {0} Members", count);

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

Categories