I'm working with C# and SQL Sever 2008, when I try to create a command for searching a record I got exception that said "Invalid Column name"
this is my code :
void cari()
{
koneksi.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = "+ textBox1.Text, koneksi);
SDA.Fill(dt);
koneksi.Close();
dataGridView1.DataSource = dt;
}`
the search command should be work as search engine, can anyone help me?
Well the immediate problem is that your WHERE clause will look something like:
where Subject = Foo
which is trying to compare the value of the Subject column with the value of the Foo column.
The hacky way of fixing this is to put quotes round the value. The better solution is to use parameterized SQL:
string sql = "SELECT * FROM jadwalkuliah where Subject = #Subject";
using (SqlConnection connection = new SqlConnection(...))
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connection))
{
connection.Open();
adapter.SelectCommand.Parameters.Add("#Subject", SqlDbType.VarChar)
.Value = textBox1.Text;
adapter.Fill(dt);
}
Additionally, note that you shouldn't be performing database accesses from a GUI thread. It's not clear whether this is a web app (in which case it's okay) or WPF/WinForms (in which case it's not).
Note that that will still try to make an exact match. For a "wildcard" match you'll need to change it to something like:
SELECT * FROM jadwalkuliah where Subject LIKE #Subject
... and add the parameter with something like "%" + textBox1.Text + "%". (You'll need to then think about escaping within that value, but that's another matter...)
You haven't quoted the value of subject:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '"+ textBox1.Text + "'",
koneksi);
Or for a contains search:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '%"+ textBox1.Text + "%'", koneksi);
You shouldn't build queries this way. It is susceptible to SQL injection attacks.
Related
After I try to output the password in the dataGrid, from the given Username in the txt_Username textbox, I get this error message:
MySql.Data.MySqlClient.MySqlException: "Unknown column 'Test' in 'where clause'"
MySqlDataAdapter da = new MySqlDataAdapter("Select Password from tbl_anmeldedaten Where Username=" + txt_Username.Text, con);
da.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
The exact cause of the error is that you are trying to execute the following query:
SELECT Password
FROM tbl_anmeldedaten
WHERE Username = Test;
Does it look like Test should have single quotes around it? Yes, it should, and you could add that to your raw query. But, concatenating a query like this in C# leaves open the possibility for SQL injection. A much better approach is to use prepared statements:
string sql = "SELECT Password FROM tbl_anmeldedaten WHERE Username = #val1";
MySqlCommand cmd = new MySqlCommand(sql, MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", txt_Username.Text);
cmd.Prepare();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// consume a record in the result set
}
You are using string concatenation which is a vector for SQL injection attacks. Perhaps the username in the text field is doing some SQL which it shouldn't be allowed to (for instance '' OR Test=1. There are plenty of resources on using parameterized queries which should remedy the problem.
I have a webform where I can display data from a mysql database on a page with a gridview. I have placed a Textbox on the webform, which I would like to search among database records.
string mysqlconnectionstring = "Server=server;Database=dataser;Uid=user;Pwd=passw;CharSet=utf8";
MySqlConnection MyConnection = new MySqlConnection(mysqlconnectionstring);
string query = "select * from Tools where NameofTool like '" + Search_txt.Text + "%'";
MySqlDataAdapter da = new MySqlDataAdapter(query, MyConnection);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1_0.DataSource = ds;
GridView1_0.DataBind();
So, if I understand the problem of extracting all the data from a datasource at the beginning, and then I want to give it the search. Of course I can interpret it wrong, sorry.
So the goal would be to get data from a DataSource, run it out with a GridView, then update the GridView according to the results.
Thanks :)
dt2.Rows.Clear();
cn.Open();
string comm = "SELECT * From Ansprechperson WHERE Name LIKE '%'+ #Firma + '%' AND KundenNr LIKE #KundenNr";
cmd = new SqlCeCommand(comm, cn);
cmd.Parameters.Add("#Firma", SqlDbType.NVarChar, 100).Value = editContactFilter.Text;
cmd.Parameters.Add("#KundenNr", SqlDbType.NVarChar, 100).Value = KundenNr;
using (adapt = new SqlCeDataAdapter(cmd))
{
adapt.Fill(dt2);
}
dataGridView2.DataSource = dt2;
cn.Close();
This is an example that worked for me. Please look into parameters to make your application SQL-Injection safe. Why Parameters protect you from SQL-Injection.
dt2 is a DataTable:
DataTable dt2 = new DataTable();
ideal approach would be search precise data from sql insdead first get all the data in data set and go for an other search.
kindly dont use inline queries like
string query = "select * from Tools where NameofTool like '" + Search_txt.Text + "%'";
instead use stored procedures. these inline queries are prone to sql injection.
so your ans would be "create a stored procedure with filter parameter"
and then bind GridView with returned data.
Im using c# .net windows form application. I have loaded names of all the tables present in a database into a combobox.
Now i need to display the contents of the selected table name.
Normally we use
SqlDataAdapter adp= new SqlDataAdapter("Select * from employee", con);
This works fine. but instead of explicitly giving table name i.e employee
i need to set it to combobox1.selected item.
I have given like this its not working:
string filename= combobox1.selecteditem;
SqlDataAdapter adp= new SqlDataAdapter("Select * from filename", con);
How can I select filename dynamically?
I think this should look like:
string filename= combobox1.selecteditem.ToString();
SqlDataAdapter adp= new SqlDataAdapter("Select * from "+filename, con);
Just use string concatenation, if you're not afraid of SQL injection:
SqlDataAdapter adp = new SqlDataAdapter("Select * from " + combobox1.selecteditem, con);
I connected an sql database in c# and now trying to put the contents into a dataset. How will I be able to do that?
My code is:
string constr = "Data Source=ECEE;Initial Catalog=Internet_Bankaciligi;User ID=sa";
SqlConnection conn = new SqlConnection(constr);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from Internet_Bankaciligi", conn);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");
myDataRow = myDataSet.Tables["IB_Account"].NewRow();
myDataRow["Account_ID"] = "NewID";
myDataRow["Branch_ID"] = "New Branch";
myDataRow["Amount"] = "New Amount";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
the line: "mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");" gives an error as 'Invalid object name 'Internet_Bankaciligi'.' but Internet_Bankaciligi is my database name.
Also if i use:
SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = selectCMD;
myAdapter.Fill(myDataSet);
then: "SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);" gives an error saying invalid syntax. How will I get it correct?
If "Internet_Bankaciligi" is your actual database name, then you can't execute a SQL command directly against it. You have to change your SQL to select from a table or a view.
Your second example doesn't work because "SELECT (*)" is not valid syntax. It should be "SELECT * FROM IB_Account"... no parentheses.
I checked this statement in Sql Server 2008:
Select (*) from <table>
It doesn't work. I never seen this syntax, not in sqlserver 2005, nor Oracle nor sqlite.
try this one:
Select * from <table>
Edit: If I were you I will try using strongly typed datasets, or even Entity Framework which both are more advance and easier to work with. Google them.
Can someone let me know what is wrong with my SQL Statement and how I can improve it?
da = new SqlDataAdapter("SELECT * FROM Guests"+" WHERE Students.name='" +
byNametextBox.Text + "'", MyConn);
An EXISTS predicate is slightly more efficient than a JOIN if you want only columns from one of the tables. Additionaly - never inject strings into SQL statements like that - you're just begging for SQL Injection attacks, or related crashes errors (Yes, I know it's a Forms application, but the same holds true. If you're searching for a name like "O'Leary", you'll get a crash).
SqlCommand cmd = new SqlCommand("SELECT * FROM Guests WHERE EXISTS (SELECT Id FROM Students WHERE Guests.StudentId = Students.Id And Students.name= #name)", MyConn);
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = byNametextBox.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
Note: Some people may argue that "SELECT *" is bad, and that you should consider specifying individual column names
You need to worry about SQL Injection. Put simply, SQL Injection is when a user is able to put arbitrary SQL statements into your query. To get around this, either use a Stored Procedure or a Parametrized SQL Query. An Example of a Parametrized SQL query is below:
SqlConnection conn = null;
SqlDataReader reader = null;
//Connection string goes here
string studentName = byNametextBox.Text;
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Guests "+" WHERE Students.name = #name", conn);
SqlParameter param = new SqlParameter("#name", SqlDbType.NVarChar, 50);
param.Value = studentName;
cmd.Parameters.Add(param);
reader = cmd.ExecuteReader();
//Do stuff with reader here
SqlDataAdapter("SELECT Guests.* FROM Guests,Students WHERE Guest.StudentId = Student.Id and Students.name='" + byNametextBox.Text + "'", MyConn);`
You need an Inner Join. I think it would be something like this:
SELECT Guests.* FROM Guests INNER JOIN Students ON Students.name = Guests.name WHERE Students.name = '" + byNametextBox.Text + "'"
Try it:
"SELECT g.*
FROM Guests g
INNER JOIN Students s ON g.StudentId = s.StudentId
WHERE Students.Name = '" + byNametextBox.Text + '"'
Assuming that the field wich relates both tables is StudentId.
Beware that SQL is not the same between different Servers. This statement will work on Sql Server, I don't know in others. Also, beware that you aren't protecting yourself on SQL Injection attacks. You should perform your query with parameters, instead of concatenating strings in the way you are doing it.
This is a simple query that you should know by yourself. You can search for tutorials on Google, but here is a generic introduction.