How to use SQL COUNT function in C# - c#

OBJECTIVE:
I am trying to get all the values in the column "test_results" from the table "test" where the studentID is the equal to some variable. I am trying to use the COUNT function in SQL to do this query however I keep getting an eror:
C# CODE:
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(test_results) FROM test WHERE test.StudentID ='" + student + "';");
ERROR:
"cannot find specificed column in results: test_results"
Which is weird because I have no table named "results". Where did I make an error?
Thank You
EDIT:
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(test_results) AS test WHERE studentID = '" + student + "';");
Gets rid of the previous error however I have another error which says:
you have an error in your SQL syntax near 'WHERE studentID = '6" at line 1

Instead of
"SELECT COUNT(test_results) FROM test WHERE test.StudentID ='" + student + "';"
Do aliasing of the column:
"SELECT COUNT(*) as test_results FROM test WHERE test.StudentID ='" + student + "';"
Also, always use parameterized statement. See this post to know more:
Why do we always prefer using parameters in SQL statements?

Related

SQLite searching for user in table

// This returns a count of 1, so the table does exist, and I know the user exists becaue I have just added him in...
Int32 tableCount = database.Query(map, "SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'UserTable'", ps).Count;
//but when I try this the count is 0....what am I doing wrong?
Int32 tableCount2 = database.Query(map, "SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'UserTable' AND NameOfUser = '" + personsName + "'", ps).Count;
t
rying to see if the user exists...what am I doing wrong?
SQL Injections
First, I want to say that this code is vulnerable to SQL Injections, .
Why does the query not work?
Because 'NameOfUser' is not a column of sqlite_master, but it is a column of UserTable, I suppose.
sqlite_master consists of the following columns:
type
name
tbl_name
rootpage
sql
How can I make it work?
Int32 tableCount2 = database.Query(map, "SELECT * FROM UserTable WHERE NameOfUser = '" + personsName + "'", ps).Count;
But, as said before, you better use C# SQLite prepared statements to prevent SQL injection, check this: C# SQLite tutorial and search for 'prepared'
Please mark as answer when it worked.
CU

C# Alter Table and Add a column programmatically ASP.Net & SQL Server

I have been trying to add a column programmatically in ASP.NET to modify the tables in SQL Server.
Please see the following code:
string suppliernotxt = supplieridlist[1].ToString();
//SqlCommand cmd2 = new SqlCommand("ALTER TABLE [ProductNormalDB] ADD suppliernotxt nvarchar(20) NULL", con);
SqlCommand cmd2 = new SqlCommand("ALTER TABLE ProductNormalDB ADD #supplierlist nvarchar(20) NULL", con);
cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt);
//cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt.ToString());
//cmd2.Parameters["#supplierlist"].Value = supplieridlist[x];
cmd2.ExecuteNonQuery();
supplieridlist is an array that acquires all the column names to add into the SQL Server database. For some reason the parametrized method is not working and shows the following error:
Incorrect syntax near '#supplierlist'.
The basic idea is to have a user select from a check box the name of the suppliers, based on the selected number of suppliers the array will create the supplier names for ex. if we selected 3 suppliers, the array will save "Supplier1", "Supplier2", "Supplier3" and then the SqlCommand is supposed to alter the table and add the new columns.
You cannot use parameters to express the name of columns.
Parameters could only be used to express values for WHERE clause or for INSERT or UPDATE statements.
You could use string concatenation for your query text, passing the string value to a stored procedure or use some form of dynamic sql.
Please be very carefull with these kind of approaches because if you don't keep absolute control on the values passed to your code you will be exposed to Sql Injection.
Adding as an example of Dynamic SQL execution, but still vulnerable to SQL Injection
string suppliernotxt = supplieridlist[1].ToString();
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = '" + suppliernotxt + "'; " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"
SqlCommand cmd2 = new SqlCommand(execSQL, con);
cmd2.ExecuteNonQuery();
As you can see, even with Dynamic SQL there is nothing that prevent an SQL Injection attack passing via the suppliernotxt variable
EDIT As explained in the comments below from #RBarryYoung, a good improvement on the SQL Injection problem for this case of dynamic sql could be the usage of the QUOTENAME function to obtain an Unicode string with the required delimiters around the input string
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = QUOTENAME('" + suppliernotxt + "'); " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"

How to use MySql select with c#

Can anyone tell whats wrong with my code? I have tried a million different things and I cant seem to make it work. I need to make a select in my mysql database and use the id from the table with the specified name I take from a combobox.
I took that name from the combobox and put it into a variable named "nomeres", now I need to do a select with it and take the id from that name from the database. Everything I try to do results in a mysql syntax error in line 1, but I've tried alot of things and its always the same. The database is fine, I tried the select directly from it myself, no tables or columns names are incorrect. This is the code im using:
MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection("Persist Security Info=False;server=localhost;database=notas;uid=root;password=" + dbpwd);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres;
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Erro" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
}
as others have already pointed you towards right direction,
i would like to suggest you to use parameterised queries to avoid SQL injection attacks.
Your query is open to SQL injection attacks so please read here
Try This: using parameterised SQL queries
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValue("#nome",nomeres);
You need to terminate the string in the query:
"SELECT id from residentes WHERE nome ='" + nomeres + "'"
In general, when trying to debug this type of code, it helps to print out the query string after all substitutions have been made.
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres + "';";
actually you misses the semicolon of the query that have to enter within the quotes. and the second semicolon is for the end of statement.
But I preffer wo write commands like
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValues("#nome", variableName);
then execute the query and retrieve your results.
Missing single quote:
"SELECT id from residentes WHERE nome ='" + nomeres + "'";
^

Syntax error in UPDATE statement OleDb Exception

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

Cannot figure out how to fix syntax error (missing operator) in query expression error in C#

I'm having an issue with an error written above and cannot find a exact way to fix it.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from [contractors$] where " + category + " like '*#name*'", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "*" + name + "*";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
The exact error is..
Syntax error (missing operator) in query expression 'like '#name''.
I've also already looked for solutions to this problem and have attempted to adapt them to try to get this work work, but with no luck(the one above was one of the attempts)
Much thanks in advance!
Ok, so I have now change the code to this..
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from `contractors$` where " + category + " LIKE #name", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "%" + name + "%";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
But I am still getting the same error.
A parameter cannot be contained inside an SQL string literal. Use concatenation to build the string:
"... LIKE ('%' + #name + '%') ..."
Update
It seems that the value of category was null or empty, creating an invalid SQL statement:
Select count(*) from [contractors$] where like '#name'
^^^ no category here

Categories

Resources