sql query in the SqlDataAdapter() - c#

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);

Related

how to use Gridview

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.

Update/Insert MySQL values with C#

I am trying to both update and insert new database entries in my SQL database. The database runs through XAMPP because we wanted to test out if we could make it work using an external server.
I got the following code:
MySqlConnection sqlcon = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
MySqlDataAdapter mda = new MySqlDataAdapter("INSERT INTO projectDatabase.lesson (name, classRoom, TeacherID, active) VALUES ('"+ lessonName +"', '"+ className +"', '"+ UserData[0] +"', 1)", sqlcon);
MySqlDataAdapter mda2 = new MySqlDataAdapter("SELECT * FROM projectDatabase.lesson WHERE TeacherID = "+ UserData[0] +" AND active = 1", sqlcon);
sqlcon.Open();
DataSet ds = new DataSet();
mda2.Fill(ds, "lesson");
DataRow dr = ds.Tables["lesson"].Rows[0];
sqlcon.Close();
After this patch of code, the selected database items get inserted into arrays just fine, but there is no sign of an entry being added to the database.
The select works fine, but the insert (and update too for that matter) won't execute or even produce errors. I have been looking around for answers, but they all drastically change the way we have done the database queries so far. Is there a way to make it work using my current code?

Select value from database based on dropdownlist value

I have database table leave_rec(name,date1,leave,ltype), a Dropdown list and a gridview.
I want to do such that,when I select month(e.g. february) in dropdown list the gridview should display all table values for february only(e.g.rohan leuva,2/28/2013,full,casual),means record which has month=2 (february).
How to overcome this issue? I tried but I can only display all the values in gridview at this moment. Any help would be greatly appriciated.
SqlConnection conn = new SqlConnection();
conn.ConnectionString=System.Configuration.ConfigurationManager.ConnectionStrings["leave"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("select date1,leave,ltype from leave_rec where name='" + DropDownList1.SelectedValue + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
The above code displays the date1,leave,ltype for dropdownlist1.selectedvalue. But now i want to have second dropdown in which months will be there. so when i select february in second one, grid should display value for dropdownlist1.selectedvalue for february only.
First, your query needs to be something like this:
select date1, leave, ltype from leave_rec where MONTH(date1) = 2 // February
Then, integrating it into your code:
SqlCommand cmd = new SqlCommand("select date1, leave, ltype from leave_rec where MONTH(date1) = #p1", conn);
cmd.Parameters.Add(new SqlParameter("p1", combo.SelectedKey));
Use parameters instead of string concatenation to avoid SQL Injection, see an example here: http://www.dotnetperls.com/sqlparameter
(Use your own control names for "combo.SelectedKey", of course)
I think problem in query , instead of name you have to write date1
SqlCommand cmd = new SqlCommand("select date1, leave, ltype from leave_rec where MONTH(date1) ='" + DropDownList1.SelectedValue + "'", conn);
Convert the dataset to DataTable
then - Filter it by dt.Filter=monthName.toString()
then bind it to GridView - dt.DefaultView;
Agree with #Saurabh, look into the use of Linq and Stored Procedures to force the use of types and modelling.

Invalid Column name when implementing search button

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.

DataSet help in C#

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.

Categories

Resources