Access Multiple search filter [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to click a search button with multiple inputs on the textbox.
I have looked around and tried different methods but somehow It didn't work out. Below is the code for the click event:
private void btn_table_Click(object sender, EventArgs e) {
try {
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select [Name],[Sex],[Number] from RecordsSheet [Name] like('" + textBox1.Text + "%'),[Sex]=('" + textBox2.Text + "%'),[Number]=('" + textBox3.Text + "%'");
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex) {
MessageBox.Show("Error " + ex);
}
}

You are currently mixing equals and LIKE syntax on the same operations, which is going to result in some incorrectly formed queries, as well as the absence of a WHERE clause to properly use them.
Use Parameterization
If you have a specific search term, consider adding it in as a parameter with your LIKE section predefined within your query :
// Add your properties using parameters
var query = "SELECT [Name],[Sex],[Number] FROM RecordsSheet WHERE [Name] LIKE ? AND [Sex] LIKE ?,[Number] LIKE ?";
Then add your parameters along with the necessary wildcards to build your query :
OleDbDataAdapter da = new OleDbDataAdapter(command);
// Set your parameters
da.SelectCommand.Parameters.AddWithValue("p1",textBox1.Text + "*");
da.SelectCommand.Parameters.AddWithValue("p2",textBox2.Text + "*");
da.SelectCommand.Parameters.AddWithValue("p3",textBox3.Text + "*");
This approach will not only lead to resolving issues related to syntax, but it should also help keep you protected from nasty things like SQL Injection attacks.

with [Sex] and [Number] replace "=" with "like", that may help..
if not post the result description.

Related

Deleting and updating tables in Microsoft SQL Server using C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I am using the following code to add items to the table but I have troubles deleting or updating items in the table. I am trying commands like
delete from MyTable
values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
and the command is accepted but the item is not deleted.
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into MyTable values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item inserted");
It is a bit hard to find resources since google just shows, sql or mysql when I try to search for a solution.
Why would you expect an SQL command based on the INSERT keyword to delete a record?
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
DELETE
FROM MyTable
WHERE MyColumn= #SomeValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
Pay special attention to how I used a query parameter. The string concatenation technique in the question is NEVER okay, and is the easiest way I've seen to find out a year from now you were hacked six months ago.
To change (update) a record, you must write an UPDATE query:
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
UPDATE MyTable
Set SomeColumn = #SomeValue
WHERE SomeOtherColumn = #SomeOtherValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox2.Text;
cmd.Parameters.Add("#SomeOtherValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
The thing to understand about this is you do not delete or update a record by specifying all the fields in a VALUES() clause, as you would with an INSERT. Instead, you use a WHERE clause and only need to include enough for the conditional expressions to identify which row(s) you want to change or delete. An UPDATE statement will then further specify what to change via the SET clause.

What is the reason for my SqlException: Incorrect syntax near '='? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source = LAPTOP-ULT25NKH; database = college;integrated security = True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from teacher where tID = " + textBox1.Text + "";
DataSet DS = new DataSet();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
but I get this exception:
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 '='."
Ensure you are properly santizing inputs and using prepared statements; to start down the line for you, try:
cmd.CommandText = "SELECT * FROM teacher WHERE tID = #tID;"
SqlParameter idParam = new SqlParameter("#tID", SqlDbType.NVarChar , 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();
There are lot of issues in your existing code, I’m mentioning few points brlow.
Please move the connection string to some config file, it’s easy to maintain there.
When you have DataAdapter you don’t need to explicitly open the connection, it does that for you internally.
Please avoid * in select query, mention the columns with alias and use parameterized query to pass the parameters. Or your can write stored procedure and call it. So that I if I’m future you need to modify query, there will be no code change.
If you need to open the connection, please close it or your can use using.
You can add breakpoint and see the value of your query and if you copy this query value and run in sql server directly . This is one way to find the error in the query.

sql query in c# using visual studio [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Problem is in select query it's not working exception occur near textBox1.Text :
private void button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * From '"+textBox1.Text+"'", con);
sda.SelectCommand.ExecuteNonQuery();
DataTable dtable = new DataTable();
sda.Fill(dtable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dtable;
dataGridView1.DataSource = bSource;
sda.Update(dtable);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Take a look at your query. Problem is you are quoting your table name and so it's considered as string literal rather a table name
"select * From '"+textBox1.Text+"'"
^... Here
Again, you are using ExecuteNonQuery() instead of ExecuteReader()
Your query is prone to SQL Injection and I don't think you can pass table name as parameter to DB. If this is your real requirement then consider using a Dynamic Query rather. A sample using s stored procedure like
create procedure usp_selectData(#tblname nvarchar(100))
as begin
declare #sql nvarchar(200);
if (exists (select * from information_schema.tables
where table_name = #tblname))
begin
set #sql = 'select * from ' + #tblname;
exec(#sql);
end
end

Error when execute query [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
HI here is code snippet of C#. I am trying to generate a summary of data and display in formview in asp.net. But having a issue with this code generating error that
'Incorrect syntax near 'K12'.'
please help me out.
try
{
SqlConnection conn = new SqlConnection("server=ARSLAN- LAPI\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=OTTS; " +
"connection timeout=30");
String query = "Select * FROM dbo.";
query = query + " " + "[" + session.SelectedItem.Text + "_" + dept.SelectedItem.Text + "]";
query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37";
//SqlCommand cmd = new SqlCommand(query, conn);
//SqlDataReader reader;
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, conn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dataform.DataSource = table;
dataform.Visible = true;
}
catch (SqlException ex)
{
ErrorMessage.Text="Error ::"+ ex.Message;
}
The roll number string in your where clause needs to be delimited as a string. This line query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37"; should be replaced with query += " " + "WHERE rollNo=" + "'2K12-BSCS-37'"; Note the single quotes.
Better still would be to use string format to build your query, something like this:
string.Format("SELECT * FROM dbo.[{0}_{1}] WHERE rollNo = '{2}'",
session.SelectedItem.Text,
dept.SelectedItem.Text,
"2K12-BSCS-37")
And even better still would be to avoid this dangerous query altogether, since it exposes your database to numerous possible attacks. I have honestly never let users build their own table name in this fashion, so I can't even say if the SQLClient parameters would work here, though I expect they will not. I agree with previous comments that much range checking, etc. will be required to make this viable.
In the end, hopefully this is an internal application that only a select few users will ever have access to.

How to search data in database and add it to textboxes in C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have multiple data in database so i need to add them in different textBoxes.
here is my code
private void Search_button1_Click(object sender, EventArgs e)
{
string query = string.Empty;
if (ID_textBox1.Text.Trim().Length > 0)
{
try
{
query = "SELECT ProductName,ProductDescription,SellPrice FROM Table2 WHERE ProductID='" + ID_textBox1.Text + "'";
SqlConnection Conn = CreateConnection.create_connection();
SqlCommand cd = new SqlCommand(query, Conn);
SqlDataReader reader = cd.ExecuteReader();
while (reader.Read())
{
Name_textBox2.Text = reader["ProductName"].ToString();
Description_textBox3.Text = reader["ProductDescription"].ToString();
Unit_Price_textBox5.Text = reader["SellPrice"].ToString();
}
reader.Close();
Name_textBox2.Text = Name_textBox2.Text;
Description_textBox3.Text = Description_textBox3.Text;
QTY_textBox4.Text = 1.ToString();
Unit_Price_textBox5.Text = Unit_Price_textBox5.Text;
Price_textBox6.Text = (decimal.Parse(QTY_textBox4.Text) * decimal.Parse(Unit_Price_textBox5.Text)).ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
You didn't state what your problem is, but there are a couple of things I'd suggest doing.
Use Parameterized Queries. This will prevent SQL Injection attacks.
Use the using statement to ensure things are properly disposed of.
Line like this: Name_textBox2.Text = Name_textBox2.Text; are unnecessary - you're simply assigning the value back to itself.
1.ToString() doesn't make any sense. 1 is not a valid variable name. If you're wanting to assign the value of 1 to the textbox, simply use QTY_textBox4.Text = "1";.
I would rewrite your code to look like this:
if (ID_textBox1.Text.Trim().Length > 0)
{
try
{
query = "SELECT ProductName,ProductDescription,SellPrice FROM Table2 WHERE ProductID=#ProductID";
using (SqlConnection Conn = CreateConnection.create_connection())
{
// NOTE: If CreateConnection.create_connection() does not return
// an opened connection, you will need to open it like this:
// Conn.Open();
SqlCommand cd = new SqlCommand(query, Conn);
cd.Parameters.AddWithValue("#ProductID", ID_textBox1.Text);
using (SqlDataReader reader = cd.ExecuteReader())
{
while (reader.Read())
{
Name_textBox2.Text = reader["ProductName"].ToString();
Description_textBox3.Text = reader["ProductDescription"].ToString();
Unit_Price_textBox5.Text = reader["SellPrice"].ToString();
}
}
}
decimal quantity;
decimal unitPrice;
QTY_textBox4.Text = "1";
decimal.TryParse(QTY_textBox4.Text, out quantity);
decimal.TryParse(Unit_Price_textBox5.Text, unitPrice);
Price_textBox6.Text = (quantity * unitPrice).ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The above code uses a parameterized query - "SELECT ProductName,ProductDescription,SellPrice FROM Table2 WHERE ProductID=#ProductID". The #ProductID is a placeholder for a parameter.
That parameter is populated by the cd.Parameters.AddWithValue("#ProductID", ID_textBox1.Text); line.
using statements are used for the SqlConnection and the SqlDataReader, and will ensure the objects are properly closed and disposed of, even if an exception occurs.
I removed the unncessary lines where the TextBox's where being assigned their current values, as that's done in the loop above.
Finally, I suggest using TryParse, as that will not throw an error if the parse is unsuccessful. In fact, you could use TryParse to show a message if the parse wasn't successful (TryParse returns a boolean).
Based on the query, I'm guessing you only expect one row of data, but if you get multiple rows of data, only the last row will be the final values in the TextBoxes.
Without more information, we can tell you much more than this. I hope it helps.

Categories