% characters unexpectedly added in the middle of filename or folder name - c#

I have web search form, When i submit my search in the search box,
The result are returned but with contains % in the file name.
for example. the original file name is abc.jpeg, so the result returned will be a%bc.
or if a folder is found with, so its the same for the folder name.
if a folder name is jack, in the result it will be ja%ck.
I have the text box (as a search box, and i have set the value of the search text box as) <%search text%>
Thanks for the help and taking time to read it.
I am using Asp.net, C# and Access DB.
code :
iscBuilder.AddSelect("* ");
iscBuilder.AddFrom("[table1] ");
iscBuilder.AddWhereClause("( column_name like('%" + pQuery + "%') or column_name like('%" + pQuery + "%') or column_name like('" + pQuery + "%') or column_name like('" + pQuery + "%') )");
iscBuilder.AddWhereClause("(column_name like( '" + path + "') or column_name like( '" + path + "')) order by column_name");
OleDbConnection sqlconConnection = (OleDbConnection)DatabaseConnection.Instance.GetConnection();
OleDbCommand sqlcmdCommand1 = new OleDbCommand(iscBuilder.ToString(), sqlconConnection);
sqlcmdCommand1.CommandType = CommandType.Text;
This is how i call the function: public XmlDocument GetSearchResults(string pQuery, string path,int from , int to)
{
List <T> ts= T.GetF().Getresult(pQuery, path);
return createXMLThumnails(thmbNails,from , to);
}
Have nice day

Try using a parameterised query or stored procedure to get your data - all this joining strings to make SQL statements is very fiddly and problematic.
Have a look at using Parameterised Queries or Stored Procedures.

Related

C# SQL SELECT WHERE <variable> LIKE %Column% - format?

Currently I am using this statement:
"SELECT categoryDB, number FROM " + dbName+ " WHERE titleDBColumn ='" + titleInput+ "'";
Which helps me find strings that are similar to titleInput (which is a variable coming from the outside).
However, the values in titleDBColumn are almost always shorter strings than those coming in through titleInput.
Example:
titleDBColumn: Streetcar
titleInput: TheStreetCarIOwn
Now it's obvious that I need to use the LIKE operator in the other direction to get the results I want but I cant get the format right. Any ideas?
Sorry if I'm unclear.
This worked for me:
"SELECT categoryDB, number FROM " + dbName + " WHERE '" +
titleInput + "' like '%' + titleDBColumn + '%'";
The resulting SQL must be
SELECT categoryDB, number
FROM tableName
WHERE 'input' LIKE '%' + titleDBColumn + '%'
The % wildcard means "any number of any characters". I.e, 'input' LIKE '%' + titleDBColumn + '%' means that the input text may contain characters before and after the column text.
Also, you should use command parameters, whenever possible. This is not possible for the table name you called dbName. If this name is defined in the code and is not a user input, then it is safe to concatenate it as you did. But otherwise take measures to prevent SQL-Injection.
string sql = "SELECT categoryDB, number FROM `" + dbName +
"` WHERE #input LIKE '%' + titleDBColumn + '%'";
using (var conn = new MySqlConnection(connStr)) {
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#input", titleInput);
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
...
}
}

Storing Data in SQLite

Is there a way to store TEXT in SQLite database without SQLite trying to parse it?
Ran into a problem where when you store TEXT that is similar to SQLite query, it tries to parse it for some reason.
Query I use to save TEXT: "insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".
Similar text I'm trying to save: "SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".
When i try to save something like that, it says: Error: SQL logic error or missing database near "table":syntax error
Please note that values (name, currentDate, reminder, content) are not hard coded, they are passed as strings. actual code is like below:
SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);
Thanks for any input.
As I suspect, the problem is that you're putting your values directly into the SQL - without even trying to escape them. Don't do that. As well as the problems you're seeing, you've opened yourself up to a SQL injection attack. Use parameterized SQL instead, and specify values for the parameters.
For example:
// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
" (Name, DateCreated, Reminder, Content) values " +
"(#Name, #DateCreated, #Reminder, #Content)");
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.Add("#Name", SQLiteType.Text).Value = noteName;
command.Parameters.Add("#DateCreated", SQLiteType.DateTime).Value = currentDate;
command.Parameters.Add("#Reminder", SQLiteType.Text).Value = reminder;
command.Parameters.Add("#Content", SQLiteType.Text).Value = content;
command.ExecuteNonQuery();
}

C# database application using Ms access 2010

I am developing a database application on C# using MS Access for my perfume shop, i have created a table in ms access, named as "MIX", having columns (Brand name,Stock quantity,Retail price,Original price). I want to add their field through C# window form that i have created.
I am trying the following query for inserting my data but all the time i am getting an error "Syntax error in INSERT INTO statement"
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string str = string.Format("Insert into MIX([Brand name],Stock quantity,Retail price,Original price)Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfull");
cmd.Dispose();
}
Four things:
You don't need string.Format when you're just concatenating values
Column names with spaces must be surrounded by square brackets:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")";
You should learn how to use Parameters instead of concatenating SQL:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values (?,?,?,?)");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.Parameters.AddWithValue("brand",textBox1.Text);
... repeat for other values
It appears you're reusing a shared OleDbConnection object. This is not a best practice since connections are pooled in .NET and are cheap to recreate after the first usage, and you don't hae to worry about leaving a connection open throughout the life of your application.
This is a really bad idea since the values are being directly dropped into the query, but the problem you are experiencing is the multi-word column names:
Insert into MIX([Brand name],Stock quantity,Retail price,Original price)
These need to have bracket around them:
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])[
You need to enclose column names that contain spaces insquare brackets []. Also, you need to use parameters instead of concatenating values to the SQL query like that. Google "SQL injection attack" to know the reason why.
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])Values(?,?,?,?)
You replace those ?'s with values this way:
cmd.Parameters.AddWithValue("?", Textbox1.text);
cmd.Parameters.AddWithValue("?", Textbox2.text);
cmd.Parameters.AddWithValue("?", Textbox3.text);
cmd.Parameters.AddWithValue("?", Textbox4.text);
Be aware that the order matters.

Mysql syntax error (insert inti) using c#

this how is my table look like, and this is my query
query = "insert into archive.exports (DocumentID, from, to, sendDate, dadbox, sonbox, sendBy) values(" + DocumentNum + ", " + from + ", " + to + ", '" + this.date.Value.ToShortDateString() + "', " + DadBox + ", " + SunBox + ", '" + SendBy + "')";
it gave me this error
can someone tell me where is the error, Sorry for my bad english
from and to are Reserved Keywords and happens to be the name of your column. In order to avoid syntax error, the column name should be escaped using backticks. Ex,
INSERT INTO archive.exports (DocumentID, `from`, `to`,...)
MySQL Reserved Keywords List
If you have the privilege to alter the table, change the column name that is not on the Reserved Keyword List to prevent the same error from getting back again on the future.

MySql reading parameter name as column during insert

This should be really simple. Basically I'm just inserting data into the table:
string sql = "insert into Files(filename, filedate, filedata, filesize) values(xname, xdate, xdata, xsize);select last_insert_id() as lastid from Files";
The values specified here (xname, xdate, etc) are just parameters and I'm setting their values before executing the query.
Unfortunately, something's gone wrong and I'm getting the following error:
Unknown column 'xname' in 'field list'
I can understand that for some or other reason, it's looking for a column named "xname" which, obviously doesn't exist. What I can't understand is why it's doing this.
Typically I "tag" parameters with the # symbol (#name, #date, etc) which generally works, but I'm working on a system written by another developer in the company and I have to maintain conventions.
Can anyone explain why I'm getting this error?
If xname, xdate, xdata and xsize are variables, then you could do something like:
string sql = "insert into Files(filename, filedate, filedata, filesize) values(" +
xname + ", " + xdate + ", " +
xdata + ", " + xsize +
");select last_insert_id() as lastid from Files";

Categories