ok thanks alot for all who help me ,but now i have another problem i want to get this statement correct also
if (byNametextBox.Text != null && byBuildingtextBox.Text !=null && seTextBoxPublic1.Text == null)
{
da = new SqlDataAdapter("SELECT * FROM Students WHERE name='" + byNametextBox.Text +"and [buil-id]='"+byBuildingtextBox.Text+ "'", MyConn);
}
i want to select from the same table with two condition
please
Please use parameters! If for some reason you're against them, this should work:
string strStatement = String.Format("SELECT * FROM Students WHERE [name] = '{0}' AND [buil-id] = '{1}'", byNametextBox.Text, byBuildingtextBox.Text);
da = new SqlDataAdapter(strStatement, MyConn);
Better for security if you use parameters in your SQL query.
I suppose you should create an SqlCommand with 2 parameters.
The code you posted here is not safe for SQL Injection attacks.
Please follow:
http://msdn.microsoft.com/en-us/library/ms161953.aspx
To answer your question, however, your code creates the SQL:
SELECT * FROM Students WHERE name='NAMEand [buil-id]='ID'
should be
SELECT * FROM Students WHERE name='NAME' and [buil-id]='ID'
Use parameterized query to prevent sql injection, also here some additional codes if you want to populate datatable.
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students WHERE name = #byName and [buil-id]= #byBuilding " , MyConn)
DataTable dt= new DataTable();
da.SelectCommand.Parameters.AddWithValue("#byName", byNametextBox.Text);
da.SelectCommand.Parameters.AddWithValue("#byBuilding", byBuildingtextBox.Text);
da.Fill(dt);
Related
System.Data.SqlClient.SqlException: 'Ambiguous column name
'SchoolID'.'
I need to select a SchoolName == SchoolID and an AcademicYear from two combo-boxes that are found in two database tables School-Info and School_AcademicYear
Also SchoolID in School_AcademicYear is Foreign Key and its Primary Key in School_Info, I am using inner join to join these two tables but an error is occuring
Ambiguous column name 'SchoolID'
con.Open();
adp = new SqlDataAdapter("SELECT AcademicYearID,AcademicYear,SchoolID FROM School_AcademicYear INNER JOIN School_Info ON School_AcademicYear.AcademicYearID = School_Info.SchoolID where School_AcademicYear.AcademicYearID = '" + AcademicYearID + "'", con);
dt = new DataTable();
adp.Fill(dt);
dataGridViewSchoolNMergeAcYear.DataSource = dt;
con.Close();
If you join two tables that contain columns with the same name and you refer to one of these columns in the SELECT list, then you need to specify from which table are you getting the values. So to solve this problem let's start using some alias for the table names. Using the alias in front of the column's name correctly identify the columns source table.
While at it, I have also changed your string concatenation to a parameterized query. It is a lot better because it avoids parsing errors and a well known security problem called Sql Injection
using(SqlConnection con = new SqlConnection(.......))
{
string cmdText = #"SELECT a.AcademicYearID,a.AcademicYear,i.SchoolID
FROM School_AcademicYear a INNER JOIN School_Info i
ON a.AcademicYearID = i.SchoolID
WHERE a.AcademicYearID = #id";
con.Open();
adp = new SqlDataAdapter(cmdText, con);
adp.SelectCommand.Parameters.Add("#id", SqlDbType.Int).Value = AcademicYearID;
dt = new DataTable();
adp.Fill(dt);
dataGridViewSchoolNMergeAcYear.DataSource = dt;
}
To be complete this answer introduces also the using statement around the disposable connection object. In this way the connection is closed and disposed when the code exits the using block. Note that I suppose that AcademicYearID is a number and not a string so, the parameter is of type SqlDbType.Int instead of NVarChar.
You have multiple columns in those tables with name SchoolID.
You have to specify the column name, because sql cannot know which one you want. Example: School_Info.SchoolID
adp = new SqlDataAdapter(`
SELECT AcademicYearID,AcademicYear,School_Info.SchoolID
FROM School_AcademicYear
INNER JOIN School_Info ON School_AcademicYear.AcademicYearID = School_Info.SchoolID
where School_AcademicYear.AcademicYearID = '` + AcademicYearID + "'", con);
Is it possible to create an extendable SQL query in Visual studio?
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select geneID from Table3 where geneID in(" + filterdata + ")";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Can this be extended to select any possible parameter from any possible tables using any possible conditions. I think it would look something like the following:
Select [Variable 1,Variable 2...] from [Table 1, Table2...] where [Condition1, Condition 2...]
The variables, tables and conditions in this case will be selected using a multitude of checkbox's. I want to incorporate any possible search into one button click.
Use sql joins ..Inside your commenttext like select a.row,b.rowtwo from tableone a inner join tabletwo b on a.row = b.row where a.row = your values
You can use the String.Format method
Converts the value of objects to strings based on the formats specified and inserts them into another string.
If you are new to the String.Format method, see the Getting started with the String.Format method section for a quick overview.
So you can use like that
cmd.CommandText = String.Format("Select {0} from {1} where {2}", columns, tables, conditions)
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.
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.
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.