Why my code show this message
Data type mismatch in criteria expression.
The attribute Fine is in number datatype.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from Studentbook where Student_ID='" + textsearch.Text + "'";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteScalar());
connection.Close();
MessageBox.Show(a.ToString(), "Your FINE is", MessageBoxButtons.OK);
Other than possible SQL Injection vulnerability; the said error could be because of the WHERE part in your query; where Student_ID is number and you are trying to compare it with string type data.
where Student_ID='" + textsearch.Text + "'"
Considering that your Student_ID is of INT or NUMBER type column change your code to be like below. Notice the use of parameterized query to avoid SQL Injection
string sql = "select sum(Fine) from Studentbook where Student_ID = #studentid";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#studentid", Convert.ToInt32(textsearch.Text.Trim()));
Related
executenonquery() error c#
this is how my code looks like
con.Open();
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);
String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);
String field = comboBox1.SelectedItem.ToString();
String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
executenonquery() always makes me problem !
int i = cmd.ExecuteNonQuery();
You need to fix a couple of things:
Remove the last , in your query.
I don't know if you have a table named Table in your database but you should check if the name is correct.
When you don't know how to correct your code it's better use the try-catch statement to understand where the real problem is in your code. Here is an example about how to handle SQL exception in C# code.
You are getting SqlException because your query syntax is wrong but there is another way to add SQL parameters into your query without need to use a string variable. You could use the SqlParameterCollection.AddWithValue(String, Object) method to achieve the same result and avoid SQL Injection:
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (#name, #address, #id, #semester, #field)";
command.Parameters.AddWithValue("#name", name);
command.Parameters.AddWithValue("#address", address);
command.Parameters.AddWithValue("#id", iid);
command.Parameters.AddWithValue("#semester", i_sem);
command.Parameters.AddWithValue("#field", field);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close(); //close your connection if you do not need to keep it open
}
More info:
AddWithValue Method
SQL Injection
Other examples related to this topic
When I run this code, the following error occurs
ExecuteNonQuery: CommandText property has not been initialized
Code:
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
if (Request.QueryString["search"] != null)
{
cmd.CommandText = "Select * from Products where ProductName like('%" + Request.QueryString["search"].ToString() + "%')";
}
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dlProduct.DataSource = dt;
dlProduct.DataBind();
con.Close();
This would happen if you didn't have a search query-string parameter - you would never assign to CommandText.
However: please please please never write code like this; this is a SQL Injection hole that would let anyone own your database trivially. Please use ADO.NET parameters, or data access tools that do it for you.
Example:
string q = Request.QueryString["search"] ?? "";
cmd.CommandText = "Select * from Products where ProductName like N'%' + #q + N'%'";
cmd.Parameters.AddWithValue("#q", q);
Also: the cmd.ExecuteNonQuery(); does nothing useful - so just throw that away.
Since you are setting CommandText conditionally and the condition is false thats why you are getting error. Ensure you have search in querystring and also use parameterized query instead of embedding the value in queries to prevent sql injection
if (Request.QueryString["search"] != null)
{
cmd.CommandText = "Select * from Products where ProductName like('%" + Request.QueryString["search"].ToString() + "%')";
}
I am trying to update an access table with the code noted below. however, the update does not execute. It doesn't give me any errors but it doesn't update the database. Any suggestions?
string Const = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Db\\test.accdb";
OleDbCommand Cmd;
OleDbConnection con22 = new OleDbConnection(Const );
con22.Open();
string sql = "UPDATE CostT SET tFormSent='" + Selection1.Text + "',TName='" + UserName.Text + "',FormDate='" + FormDate.Text + "',where ReqNum=" + ReqNum.Text;
cmd = new OleDbCommand(sql, con22);
cmd.ExecuteNonQuery();
con22.Close();
MessageBox.Show("Form has been Updated");
Try changing the query
to
string sql = "UPDATE CostT SET tFormSent = #selection1,TName = #UserName,FormDate = #FormDate where ReqNum = #ReqNum";
cmd = new OleDbCommand(sql, con22);
cmd.Parameters.Add("#selection1", Selection1.Text);
cmd.Parameters.Add("#UserName", UserName.Text);
cmd.Parameters.Add("#FromDate", FromDate.Text);
cmd.Parameters.Add("#ReqNum", ReqNum.Text);
cmd.ExecuteNonQuery();
con22.Close();
Your query has a syntax error: you have a comma before your WHERE clause that does not belong there.
But more important: Your code is open to SQL injection! Please don't insert user input directly into your query, but use parameterized queries instead!
I think I'm making a fairly amateur mistake somewhere here, but I can't get SQL Parameters to reliably work in C#. Consider the following code:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT " + fieldToReturn + " FROM " + tableName + " WHERE " + fieldToCheck " = '" + dataToFind "'";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
This executes as you would expect, returning the fieldToReturn from the table tableName. However, I understand that this is vulnerably to SQL injections, and that the correct way to avoid this is to use parameters. So I change my code to the following:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = new SqlParameter("#dataToFind", dataToFind);
parameters[1] = new SqlParameter("#name", tableName);
parameters[2] = new SqlParameter("#fieldToCheck", fieldToCheck);
parameters[3] = new SqlParameter("#fieldToReturn", fieldToReturn);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.Parameters.AddRange(parameters);
command.CommandText = "SELECT #fieldToReturn FROM #tableName WHERE #fieldToCheck = #dataToReturn";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
If I have 3 matches in my database, the first code example returns 3 matches. The second code returns 0 results?!
Am I being stupid and missing something obvious?
Your parameters are:
#dataToFind
#name
#fieldToCheck
#fieldToReturn
Your Query's CommandText has:
#fieldToReturn
#tableName
#fieldToCheck
#dataToReturn
These do not match. They must match in order to be properly applied.
i m trying to retrieve the Specialization ID from a table called Specializationtbl, using C# MSVS 2008 and the table includes SpecializationName and SpecializationID beside some other rows and my question is related to some error " No Data to present ", the command goes as bellow:
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();
SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());
DBcnction.Close();
i also tried to Select the "SpecID" instead of all the rows, but cant seem to seal the query correctly and keep receiving "No data present " error, any idea where am i making the mistake?
1) Try opening DBcnction before assigning the value to READSPecID
DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
2) Run the command in SSMS:
SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'
and see if any results are returned
3) Check comboBox1.Text has a value in it
4) Validate the contents of comboBox1.Text (Or use paremetrised queries or a stored procedure) to ensure you do not become a victim of SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Refactor to solve your TWO problems:
Your SQL injection problem when building your SQL statement.
Use ExecuteScalar if you only need one value.
Implement using blocks.
string retVal;
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);
If you really needed more than one value from your statement:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Customer c = new Customer {
ID = dr["SpecID"].ToString(),
Value = dr["Value2"].ToString(),
};
}
}
Need to first test if there are any rows. I suspect the query is returning zero rows.
if (ReadSpecID_.HasRows)
{
ReadSpecID_.Read();
}