Error on passing values in SqlCommand query - c#

What am I doing wrong here? I just want a dynamic method which can count any column depending on the value. But getting a runtime error.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='."
public class DataAccessLayerPayroll
{
public static string CountTblColumByValue(string columName,string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where"+columName+"='"+value+"'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
con.Open();
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}

The issue here is that you're missing some space between where "+columName+"= '"+value+"'"
But the bigger issue is that your command is exposed to SQL injection. To prevent this use parameterized queries.
Change it as the following way
public static string CountTblColumByValue(string columnName, string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count(#myColumName) from tblAttendance1 where #myColumName = #myValue ";
using(SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
con.Open();
cmd.Parameters.AddWithValue("#myColumName", columnName);
cmd.Parameters.AddWithValue("#myValue", value);
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}

string sqlQuery ="Select Count("+columName+") from tblAttendance1 whereYOU ARE MISSING A SPACE HERE"+columName+"='"+value+"'";
So your code must be like following:
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where "+columName+"='"+value+"'";

The basic error in your code is missing space between where and =
Also, You should definitely fix the SqlInjection as suggested in other answers. (You cannot use parameters for column name though)
After that, you also should see that according to Count definition you will only get count of not null values.
Count() function returns the number of records in a select query (only Not Null) values.
Also see how will you achieve following:
1) count null values only
2) count all not null values
3) count number/date operations i.e. <, >, between
If you don’t need these scenarios in your code, then you have the answer to the error in your sql.

Related

String or binary data would be truncated. but i can't save it other way

I have this code where I'm trying to update the value of the column consultas_marcadas with a string, here is the function that does that (this function is in a class called "dataclass"):
public bool SetValorPaciente(String nome, String coluna, String valor)
{
bool flag = false;
string strCmd = "UPDATE Paciente SET #coluna = #valor WHERE nome = #nome; ";
using (SqlConnection objConn = new SqlConnection(conString))
using (SqlCommand objCmd = new SqlCommand(strCmd, objConn))
{
objCmd.Parameters.AddWithValue("#coluna", coluna);
objCmd.Parameters.AddWithValue("#valor", valor);
objCmd.Parameters.AddWithValue("#nome", nome);
objConn.Open();
objCmd.ExecuteNonQuery();
flag = true;
objConn.Close();
}
return flag;
}
And here is where it's getting the value of the condition (nome), column to update (consultas_marcadas) and the value to update (consultas) which are all strings by the way.
dataclass datac = new dataclass();
bool valor = datac.SetValorPaciente(nome, "Consultas_Marcadas", consulta);
when I try to run the code I keep getting this error:
'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.
String or binary data would be truncated.
which after digging around for answers seems to show up because my column (consultas_marcadas in this case) only accepts smaller strings than the one I'm giving, now that is a problem that I can't seem to get past:
I have changed my column data type from Varchar(Max) to NVarchar(Max) and even to TEXT but that still didn't work;
I have tried to change the string consulta and make it just the first word, and that didn't give me any errors but it also never updated the table which is weird.
So given that I'm asking for 2 things:
Is it possible to stop getting this error?
What is the best method for saving long strings? Maybe SQL is not the thing I should be looking for, maybe there's a way to save this text to a file and then save that file somewhere and read it later, what do real programmers who have to deal with long strings every day do?
Based on your description, you want to solve the error without throwing the exception.
First, We need to create the following table in database if all the fields are string type.
Second, you can use the following code to update your database.
public bool SetValorPaciente(String nome, String coluna, String valor)
{
bool flag = false;
string strCmd = "UPDATE Paciente SET coluna = #coluna,valor=#valor WHERE nome = #nome; ";
using (SqlConnection objConn = new SqlConnection(conString))
using (SqlCommand objCmd = new SqlCommand(strCmd, objConn))
{
objCmd.Parameters.AddWithValue("#coluna", coluna);
objCmd.Parameters.AddWithValue("#valor", valor);
objCmd.Parameters.AddWithValue("#nome", nome);
objConn.Open();
objCmd.ExecuteNonQuery();
flag = true;
objConn.Close();
}
return flag;
}
Note: I modified the code about strCmd sentence.
You can update the coluna and valor when you find the same value as nome.

Getting column information in SQL

I am somwhat new to SQL, so I am not sure I am going about this the right way.
I am trying to fetch data from my SQL Server database where I want to find out if checkedin is 1/0, but it needs to search on a specific user and sort after the newest date as well.
What I am trying to do is something like this:
string connectionString = ".....";
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand checkForInOrOut = new SqlCommand("SELECT CHECKEDIN from timereg ORDER BY TIME DESC LIMIT 1 WHERE UNILOGIN = '" + publiclasses.unilogin + "'", cnn);
So my question, am I doing this right? And how do I fetch the data collected, if everything was handled correctly it should return 1 or 0. Should I use some sort of SqlDataReader? I am doing this in C#/WPF
Thanks
using (SqlDataReader myReader = checkForInOrOut.ExecuteReader())
{
while (myReader.Read())
{
string value = myReader["COLUMN NAME"].ToString();
}
}
This is how you would read data from SQL, but i recommend you looking into Parameters.AddWithValue
There are some errors in your query. First WHERE goes before ORDER BY and LIMIT is an MySql keyword while you are using the Sql Server classes. So you should use TOP value instead.
int checkedIn = 0;
string cmdText = #"SELECT TOP 1 CHECKEDIN from timereg
WHERE UNILOGIN = #unilogin
ORDER BY TIME DESC";
string connectionString = ".....";
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand checkForInOrOut = new SqlCommand(cmdText, cnn))
{
cnn.Open();
checkForInOrOut.Parameters.Add("#unilogin", SqlDbType.NVarChar).Value = publiclasses.unilogin;
// You return just one row and one column,
// so the best method to use is ExecuteScalar
object result = checkForInOrOut.ExecuteScalar();
// ExecuteScalar returns null if there is no match for your where condition
if(result != null)
{
MessageBox.Show("Login OK");
// Now convert the result variable to the exact datatype
// expected for checkedin, here I suppose you want an integer
checkedIN = Convert.ToInt32(result);
.....
}
else
MessageBox.Show("Login Failed");
}
Note how I have replaced your string concatenation with a proper use of parameters to avoid parsing problems and sql injection hacks. Finally every disposable object (connection in particular) should go inside a using block

c# Update Command to Access Database

I am trying to update data in access table. However, i keep receiving a syntax error when i attempt to update. Below is the code ive compiled. Textbox37 is the one that requires updates.
string constr1;
constr1 = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Documents\\data.accdb;Jet OLEDB:Database";
string cmdstr = "Update Log(Notes,Status)Values(#a,#b) Where LogIncNum='" + LogInc + "'";
using (OleDbConnection con1 = new OleDbConnection(constr1))
{
using (OleDbCommand com = new OleDbCommand(cmdstr, con1))
{
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#a", textBox37.Text);
com.Parameters.AddWithValue("#b", "Active");
con1.Open();
com.ExecuteNonQuery();
}
}
The correct syntax for an update statement is
UPDATE table SET field1=value1, field2=value2 WHERE field3=value3
You are using the wrong syntax hence the syntax error
As a side note, did you forget to use a parameter for the WHERE condition?
It is always correct to use a parameter for every value that you want to include in your query. Just remember to put it in the correct order because OleDb doesn't recognize the parameter by their name, but use a strictly positional order in the Parameters collection, so the first one goes assigned to the first parameter placeholder and so on.
easy way
using (var aq_pension = new System.Web.UI.WebControls.SqlDataSource())
{
aq_pension.ProviderName = "System.Data.OleDb";
aq_pension.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/stat_tresor/stat_tresor/stat_tresor/db/stat1.mdb";
aq_pension.UpdateCommand = "UPDATE tableaux1 SET nbre=0, montant_mois=0,total=0 WHERE code <>''";
aq_pension.Update();
}

SQL Syntax error in C# string

I'm running a query from a web form to update records. Since I'm just learning about C#, I'm using a command string as opposed to a stored procedure.
My update method is as follows:
public void updateOne()
{
string commandText = "update INVOICE SET <Redacted> = #<Redacted>,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
<needed a line break here, which is why I split the string again>
+ "WHERE K_INVOICE = #K_INV";
using (SqlConnection dbConnection = new SqlConnection
(conParams.connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, dbConnection);
cmd.Parameters.Add("#K_INV", SqlDbType.Int);
cmd.Parameters["#K_INV"].Value = #K_INV;
cmd.Parameters.AddWithValue("#<Redacted>", #<Redacted>.ToString());
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
cmd.Parameters.AddWithValue("#SupN", #SupN.ToString());
cmd.Parameters.AddWithValue("#Net", #Net.ToString());
cmd.Parameters.AddWithValue("VAT", #VAT.ToString());
cmd.Parameters.AddWithValue("#InvDt", #InvDt.ToString());
try
{
dbConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
errorString = e.Message.ToString();
}
}
}
Catch stalls on an SQL error (Incorrect syntax near SET), and I have an idea that the issue occurs because I convert the parameters to strings. The first parameter is an Int, which should be OK.
If this is the case, what should I convert the parameters to? If not, what on earth is wrong?
Try to add a # before the string to escape the breaklines, for sample:
string commandText = #"update INVOICE SET [Redacted] = #Redacted,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
+ "WHERE K_INVOICE = #K_INV";
In parameterName argument you can add the # but the value not, just the variable, for sample
cmd.Parameters.AddWithValue("#Redacted", redacted.ToString());
Try to execute this query in the databse with some values to check if everything is correct. You could use [brackets] in the table name and column names if you have a reserved word.
I would recommend you read this blog article on the dangers of .AddWithValue():
Can we stop using AddWithValue already?
Instead of
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
you should use
cmd.Parameters.Add("#Sup", SqlDbType.VarChar, 50).Value = ...(provide value here)..;
(is your variable in C# really called #SupN ?? Rather unusual and confusing....)
I would recommend to always define an explicit length for any string parameters you define

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);

Categories