Code below is working properly and view all matches by search in column.
string sql = "SELECT car, model, year FROM store WHERE" + column + "LIKE " + search + "'";
Now adding parameters in query. Not working. It doesn't display search in column. Only display all rows in column, if search column of column ( 1 = 1)
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = "SELECT car, model, year FROM store WHERE #column like #search '";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + searchCars.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + searchCars.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
What could possible be the answer to get it search within specific column?
Change it as follows so as to not parameterize the column name:
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = string.Format("SELECT car, model, year FROM store WHERE {0} like #search", search.GetCombo());
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
// sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + search.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + search.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
Also, you've got an extra quote at the end of your query:
like #search '";
Please take a look at this
private static void Select() {
string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE FirstName = #FirstName";
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(cmdStr, connection)) {
command.Parameters.AddWithValue("#FirstName", "John");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
}
}
}
Related
I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.
I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.
I can't see any data displayed in a gridview.
Can't see any search results.
I'm trying to use sqlparameter.
As you can see, my sqlQuery is a very long one.
If I enter 'card', it should find item_description with 'big card' or 'small card' values.
Here is my code:
searchWord = Request.Cookies["Search"].Value;
searchType = Request.Cookies["Display"].Value;
string sqlQuery;
string custSearch = searchWord;
DataTable dt = new DataTable();
SqlConnection sc = new SqlConnection(GetConnectionString());
sqlQuery = "SELECT Player.player_id AS 'ID', Player.fname AS 'First name', "
+"Player.lname AS 'Last name', Player.sport AS 'Sports',"
+"Player.position AS 'Position', Player.debut_year AS 'Debut year',"
+"Player.prof_year AS 'Major year', Player.birth_date AS 'Date of birth',"
+"Player.birth_place AS 'Place of birth', Player.team_f AS 'Current team',"
+"Player.team_s AS 'Past team1', Player.team_t AS 'Past team2',"
+"Player.living AS 'Death status' "
+"FROM Player WHERE (Player.fname LIKE '#SearchPam') "
+"OR (Player.lname LIKE '#SearchPam') OR (Player.sport LIKE '#SearchPam') "
+"OR (Player.position LIKE '#SearchPam') OR (Player.team_f LIKE '#SearchPam') "
+"OR (Player.team_s LIKE '#SearchPam') OR (Player.team_t LIKE '#SearchPam');";
try
{
sc.Open();
string result = sqlQuery;
SqlCommand cmd = new SqlCommand(result, sc);
cmd.Parameters.AddWithValue("#SearchPam", custSearch);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch{...}
finally{sc.Close();}
public string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
You can use either of the following queries, i think you will get expected output using this:
string sql = "SELECT * FROM TableA WHERE Col1 LIKE #SearchPam";
.
.
cmd.Parameters.AddWithValue("#SearchPam", "%" + txtSearch.Text + "%");
OR
string sql = "SELECT * FROM TableA WHERE Col1 LIKE '%' + #SearchPam+ '%'";
.
.
cmd.Parameters.AddWithValue("#SearchPam", txtSearch.Text);
How can I get elements from table using wildcard?
I've made code something like that.
What is wron here? Is it safe if I put this into loop ?
private void Pokaz()
{
String sql = "SELECT [element] FROM [table] LIKE #Word";
SQLiteConnection connection = new SQLiteConnection(#"Data Source=C:\Temp2\dictionary.s3db");
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
DataTable dt = new DataTable();
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
dataGridView1.DataSource = dt;
}
I changed to String sql = "SELECT [element] FROM [table] where [element] LIKE \'#Word\'";
But now I get empty result.
I tried also this method. Fixed and works. Still above not.
List<string> list = new List<string>();
string connectionString = #"Data Source=C:\Temp2\dictionary.s3db";
string sql = "SELECT [element] FROM [table] where [element] LIKE \'%dog%\' ";
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(sql, connection))
{
connection.Open();
SQLiteDataReader rd = command.ExecuteReader();
while (rd.Read())
{
list.Add(rd[0].ToString());
}
}
}
Have you tried
String insSQL = "SELECT [element] FROM [table] like #Word"; //% search with prefix and postfix
SQLiteCommand cmd = new SQLiteCommand(insSQL);
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
?
How to filter data in datagrid for example if you select the combo box in student number then input 1001 in the text field. All records in 1001 will appear in datagrid. I am using sql server
private void button2_Click(object sender, EventArgs e)
{
if (cbofilter.SelectedIndex == 0)
{
string sql;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds1 = new DataSet();
ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds1);
dbgStudentDetails.DataSource = ds1;
dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
dbgStudentDetails.Refresh();
}
else if (cbofilter.SelectedIndex == 1)
{
//string sql;
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
//SqlDataAdapter da = new SqlDataAdapter();
//DataSet ds1 = new DataSet();
//ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
//sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
//SqlCommand cmd = new SqlCommand(sql,conn);
//cmd.CommandType = CommandType.Text;
//da.SelectCommand = cmd;
//da.Fill(ds1);
// dbgStudentDetails.DataSource = ds1;
//dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
//ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + ";
dbgStudentDetails.DataSource = ds.Tables[0];
dbgStudentDetails.Refresh();
}
}
It's difficult to answer pricisely to a vague question. I guess that you'll have to adapt your SQL query with a WHERE statement containing the user input.
If 'student number' is selected in the combo box, query like this (numbers starting with):
SELECT id, name, number FROM students WHERE number LIKE #search + '%'
If 'student name' is selected, use another query (names containing):
SELECT id, name, number FROM students WHERE name LIKE '%' + #search + '%'
Please explain in what sense C# is concerned.
You don't say what is wrong with the code you commented out. You also don't say what type the Studno column is.
Have you tried something like:
ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";