Currently I am working on a project regarding C# and SQL and I have a problem regarding the SELECT function and I cannot find any solutions on-line.
The scenario is regard searching query from C# through SQL server and display the results in a Data Grid View at C#.
I'm using Visual Studio 2008 and SQL Server Studio 2008.
Before starting the project I just did a quick Windows form from Visual studio and just did a datagridview, 2 text boxes and a Search Button.
At SQL Server I have a a database with a table DVD and I want to search, from this Windows form with the DVD ID and Name.
I started with the DVD ID and implemented this code :
private void btnView_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
DataTable t = new DataTable();
string sqlString = "SELECT * From DVD where Id ='" + txtID.Text+ "'";
SqlDataAdapter dt = new SqlDataAdapter(sqlString, c);
dt.Fill(t);
dtgv1.DataSource = t;
}
and it worked :)
Then I changed the code to
string sqlString = "SELECT * From DVD where Name ='" + txtName.Text+ "'";
so that I can search with Name of the DVD but when I started the program and searched with the Name it just showed a blank database
Also is there any way that I can change the code so that I can either search with the ID or with the Name ?
Thanks for your help and time
Thoughts:
Make sure txtName.Text has a value
Try SQL select using Enterprise Manager, Toad, or some other query tool. What do you get?
Try using LIKE as example below
Worst case, maybe check the Collation for the Table, perhaps its set to 'Case Sensitive' text matching.
Both ID and Name:
SELECT * FROM DVD
WHERE Id=[ID Value]
OR Name LIKE '%[Name Value]%'
Or you could use SQLCommand with parameters like this:
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
string queryString = "SELECT * From DVD where Id = #id";
var paramId = new SqlParameter("id", SqlDbType.VarChar);
var query = new SqlCommand(queryString, c);
query.Parameters.Add(paramId);
If you really want to use an SQLDataAdapter, you can set the select command to the one I wrote above. Otherwise, you can use a dataReader and iterate through the results.
Also, using parameters like this makes your query easier to read and makes it safer to SQL injections. It should always be considered.
Edit1: If you want to search with either the Id or the Name, you can just make 2 parameters, and put an OR between the 2, and maybe use the keyword like instead of = in your query. If the values can be null, you may want to build your query dynamically, depending on the values that are not null.
Related
When I choose a value in ComboBox. How can I use them to query SQL??
I tried
private void cmb1_SelectedIndexChanged(object sender, EventArgs e)
{
string select = this.cmb1.GetItemText(this.cmb1.SelectedItem);
cm1 = new SqlCommand("select VS from DATABASE where ROUND=select", con);
ap = new SqlDataAdapter(cm1);
ds = new System.Data.DataSet();
ap.Fill(ds, "DATABASE");
cmb2.DataSource = ds.Tables[0];
cmb2.DisplayMember = "VS"; // show in combobox2
}
I want to use the variable select to query but it doesn't work.
You need to pass your select to sql parameter
string select = this.cmb1.GetItemText(this.cmb1.SelectedItem);
cm1 = new SqlCommand("select VS from DATABASE where ROUND=#round", con);
cm1.Parameters.Add("#round", SqlDbType.NVarChar, -1);
cm1.Parameters["#round"].Value = select ;
You want to be careful with simply injecting values into your SQL. If you're going to use ADO like this, I'd recommend parameters.
cm1 = new SqlCommand("select VS from DATABASE where ROUND=#ROUND", con);
cm1.Parameters.Add("#ROUND", SqlDbType.VarChar);
cm1.Parameters["#ROUND"].Value = select;
Note - I saw vantian beat me to this answer so I'll try to explain a bit more about why you should use the parameters.
When you use include values posted from a web app (or API or any application where a user can define those values) you can't simply put it inline into your SQL query. A savvy, or a**hole, user can inject their own SQL into their value and your application won't know the difference and run it. With this power, a user can do whatever they want to your data -- such as steal it, or if you're lucky, only delete it to mess with your operations.
The parameters will automatically "cleanse" your input by wrapping the proper quotes and such around it and you will have a far more secure application.
Good luck!
I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '''
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.
I am using jQuery to post back values and its successfully posting back to server I checked with Mozilla FireBug. I am using these values in the insert query in .CS file to insert data in a table. The same query runs successfully in SQL Server Management Studio but when I use this query in .CS file it's not running.
Here is my code:
public static bool SaveCell(string row, string column)
{
var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True");
using (con)
using (var command = new SqlCommand("Insert into Match_Subcategory_BusinessSector5(SubCategoryID, BusinessSector5ID)"+
"Values("+
"(Select [SubCategory].ID from SubCategory where Kategorie = '#SubCategory')," +
"(SELECT [BusinessSector5].ID FROM BusinessSector5 where Description_DE = '#BusinessSector5'));",con))
{
command.Parameters.AddWithValue("#BusinessSector5", row);
command.Parameters.AddWithValue("#SubCategory", column);
con.Open();
command.ExecuteNonQuery();
}
return true;
}
I am getting this error:
The value NULL can not be inserted into the SubCategoryID column, Test.dbo.Match_Subcategory_BusinessSector5 table. The column does not allow nulls.
Chnage
'#SubCategory'
to
#SubCategory
And
'#BusinessSector5'
to
#BusinessSector5
When using parameterized query you don't need to add anything arround the parameter name, it is not combined in your code, but being sent to the server separately (it sends the sql as you wrote it and a list of parameters). Because of that, you are protected againts sql injections and related problems.
"(Select [SubCategory].ID from SubCategory where Kategorie = #SubCategory)," +
"(SELECT [BusinessSector5].ID FROM BusinessSector5 where Description_DE = #BusinessSector5));",con))
remove quotes from your query
I want to attach a DataSet with parameterized query. Something like a user entering a value in a text box then hit submit button.
I have created a Text Field and a click button event something like :
private void Btn_GetProjDetails_Click(object sender, EventArgs e)
{
string userEnteredProjId = tab3ProjIdInput.Text;
}
but now don't know how to use this userEnteredProjId variable in my query?
I haven't tried the manually coding all the data-connections path. Instead added the GUI in VS2012 to add a data source. Then using this data source I have learned we can add datasets, and then use these DataSets to just drag and drop in our form. So I created a dataset and then dataset toolbox, I added my table and created a query but don't know how to use the userEnteredProjId in my query here.
You never want to just insert a value from a user into an SQL query because that is a huge SQL injection risk. It is better to use parameters, and better still if you do some validation on the parameters before using them. Here is a basic example of using a command parameter.
using (cmd command = new SqlCommand())
{
string sql = "Select * from table where projid=#UserEnteredProjid";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("UserEnteredProjid", your_value_here);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//do something;
}
}
Well, your query is just a string variable I'm guessing, like "select * from table". You just want to take some user entered data to augment your query:
string query = "select * from table where projid = " + UserEnteredProjid;
I have searched the net and searched the net only to not quite find the probably I am running into. I am currently having an issue getting a SqlDataAdapter to populate a DataSet. I am running Visual Studio 2008 and the query is being sent to a local instance of SqlServer 2008. If I run the query SqlServer, it does return results.
Code is as follows:
string theQuery = "select Password from Employees where employee_ID = '#EmplID'";
SqlDataAdapter theDataAdapter = new SqlDataAdapter();
theDataAdapter.SelectCommand = new SqlCommand(theQuery, conn);
theDataAdapter.SelectCommand.Parameters.Add("#EmplID", SqlDbType.VarChar).Value = "EmployeeName";
theDataAdapter.Fill(theSet);
The code to read the dataset:
foreach (DataRow theRow in theSet.Tables[0].Rows)
{
//process row info
}
If there is any more info I can supply please let me know.
You need the query to say "select Password from Employees where employee_ID = #EmplID" (no single-quotes around the parameter).
If you run this query does it return results?
select Password from Employees where employee_ID = 'EmployeeName'
My guess is "EmployeeName" should be some passed in value....
and #EmpID shouldn't have single quotes around it in the query if you're using a parameter.