help me with the following sql query - sql

could somebody correct my following query, i am novice to software development realm,
i am to a string builder object in comma separated form to my query but it's not producing desired result qyery is as follows and
string cmd = "SELECT * FROM [placed_student] WHERE passout_year=#passout AND company_id=#companyId AND course_id=#courseId AND branch_id IN('" + sb + "')";
StringBuilder sb = new
StringBuilder();
foreach (ListItem li in branch.Items)
{
if (li.Selected == true)
{
sb.Append(Convert.ToInt32(li.Value)
+", ");
}
}
li is integer value of my check box list which are getting generated may be differne at different time ...please also suggest me some good source to learn sql..

Your problem lies here:
AND branch_id IN('" + sb + "')"
You'll end up with a query like:
... AND branch_id IN('1,2,3,')
If the branch_id column is an integer, you should not be quoting it, and you should insert the commas slightly differently to avoid a trailing one, such as with:
StringBuilder sb = new StringBuilder();
String sep = "";
foreach (ListItem li in branch.Items) {
if (li.Selected == true) {
sb.Append (sep + Convert.ToInt32(li.Value));
sep = ",";
}
}
String cmd = "SELECT * FROM [placed_student] " +
"WHERE passout_year = #passout " +
"AND company_id = #companyId " +
"AND course_id = #courseId " +
"AND branch_id IN (" + sb + ")";
This works by setting the initial separator to an empty string then to a comma after adding each item. So, when adding A, B and C, you'll get "A", "A,B" and "A,B,C'. I also removes the erroneous quoting on integers.
You'll also probably need to catch the case where none of your items are selected since otherwise you'll end up with:
... AND branch_id IN ()

Related

string must be exactly one character long issue

string SqlSelectQuery = " Select * From KTS Where STAFFNAME =" + Convert.ToChar(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
textBox2.Text = (dr["JOB TITLE"].ToString());
textBox3.Text = (dr["EXTN"].ToString());
textBox4.Text = (dr["Direct No."].ToString());
textBox5.Text = (dr["MOBILE (OFFICE)"].ToString());
textBox6.Text = (dr["SNO"].ToString());
i want to load data from sql server to visual studio by entering the name of the first name for the employee and he's job title mobile ext ....blla blla blla appear in the textboxes and my error is string must be exactly one character long
Convert.ToChar(textBox1.Text) requires a single character string, otherwise it throws a FormatException.
Your query should be
string SqlSelectQuery = " Select * From KTS Where STAFFNAME ='" + Convert.ToString(textBox1.Text)+"'";
You probably should use
Convert.ToString(textBox1.Text);
instead of
Convert.ToChar(textBox1.Text);
because you can't fit a String into a Char, and the textbox content will be most likely longer than one character
As per #RupeshPandey answer, you're also missing the quote to delimit the string in your query. your instruction should be
string SqlSelectQuery = "Select * From KTS Where STAFFNAME = '" +
Convert.ToString(textBox1.Text) +
"'";

Use DataAdapter results as String for new Query

I am in the process of creating a "Related Items" feature for an online store. I have a SQL query that will pull a list of ITEMs from a Database and display them on the page but I'm trying to rig up system where the list will change depending on a few variables.
The code is below and the part I'm having trouble with is getting a usable string out of Query1 to be used as the 'results' variale in query 2.
Public Shared Function GetExtraProducts(ByVal strAddOnCat As String) As DataSet
Dim connect As New SqlConnection
Dim Data1 As New DataSet
Dim data2 As New DataSet
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=GlobalPCSQL"
connect.Open()
Dim query1 As String = ""
Dim query2 As String = ""
query1 = "SELECT StockID FROM dbo.ADDONLISTS WHERE SubCategory = 'Acer-Desktops'"
Dim command1 = New SqlDataAdapter(query1, connect)
command1.Fill(Data1)
If Data1.Tables(0).Rows.Count > 0 Then
query1 = "SELECT StockID FROM dbo.ADDONLISTS WHERE SubCategory = 'Generic'"
Dim command3 = New SqlDataAdapter(query1, connect)
command3.Fill(Data1, "StockID")
End If
Dim results As String = ""
For Each row In Data1.Tables(0).Rows
results += row.ToString() + "','"
Next
If results.Length > 2 Then
results = results.Substring(0, results.Length - 2)
End If
'results = "'HD12047' , 'TV12008'"
query2 = "SELECT stock_items.Stockcode, STOCK_GROUPS.XW_URL as stockgroup, STOCK_GROUP2S.XW_URL as stockgroup2, STOCK_MAINGROUP.XW_URL as stockmaingroup, stock_items.Stockcode as pID, stock_items.description as pName, stock_web.sales_html as pdescription, stock_web.picture_url as pImage, stock_web.picture_url as pLargeimage, stock_items.sellprice1 as pPrice, stock_items.SELLPRICE1, stock_items.SELLPRICE2, stock_items.SELLPRICE3, stock_items.SELLPRICE4, stock_items.SELLPRICE5, stock_items.SELLPRICE6, stock_items.SELLPRICE7, stock_items.SELLPRICE8, stock_items.SELLPRICE9, stock_items.status as itemtype, stock_items.SELLPRICE10 as pListPrice, stock_items.x_totalstock as pInStock, stock_items.x_webhits as pHits, stock_items.ISACTIVE, stock_items.WEB_SHOW, stock_items.X_WebBlub as X_WebBlurb, stock_items.x_webpromo as X_PROMOPAGE, stock_items.last_updated as lastupdated, stock_items.x_stockleveloverride, isnull(stock_items.Restricted_item,'N') as Restricted_item "
query2 += "FROM stock_items Left OUTER Join STOCK_WEB ON (stock_items.Stockcode = STOCK_WEB.Stockcode) LEFT OUTER JOIN STOCK_GROUPS ON (STOCK_GROUPS.GROUPNO = STOCK_ITEMS.STOCKGROUP) LEFT OUTER JOIN STOCK_GROUP2S ON (STOCK_GROUP2S.GROUPNO = STOCK_ITEMS.STOCKGROUP2) LEFT OUTER JOIN STOCK_MAINGROUP ON (STOCK_MAINGROUP.GROUPNO = STOCK_GROUPS.XW_MAINGROUP)"
query2 += "WHERE stock_items.ISACTIVE='Y' AND stock_web.picture_url IS NOT NULL "
query2 += "AND stock_items.Stockcode IN ('" + results + "')"
query2 += results
Dim command2 = New SqlDataAdapter(query2, connect)
command2.Fill(data2)
connect.Close()
Return data2
End Function
Everything works fine if I spoon feed the stock Id numbers into query 2 (in place of the ' + results + ' section, but when I try to use the string from query one all I get is
Incorrect syntax near 'System.Data.DataRow'
Which makes me think that even if I got the syntax sorted, it'l only search for System.Data.Datarow instead of the actual value of the field.
Any help would be appreciated.
A DataRow can contain many DataColumns. Even though your return DataRow contains only one DataColumn, you must still specify the DataColumn:
Dim results As String = ""
For Each row In Data1.Tables(0).Rows
results += row.Item(0).ToString() + "','" '<--- Added Item(0)'
Next
If results.Length > 2 Then
results = results.Substring(0, results.Length - 2)
End If
Also, double-check that you have an apostrophe for the first result. You might need:
Dim results As String = "'"
Finally, on an unrelated note, while the + operator can be used for string concatenation, I would recommend you use the & operator instead and only use + for numerical addition:
results &= row.Item(0).ToString() & "','" '<--- Added Item(0)'

SQL entries not showing in graph

For a school project I am trying to produce a graph that shows me all the entries between two dates from an SQL table. I am using the following code:
int bLost = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strstartDate = sdf.format(startDate.getDate());
String strendDate = sdf.format(endDate.getDate());
try {
conn = JavaConnect.ConnecrDb();
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= " + strstartDate
+ " AND Datecreated <=" + strendDate );
rsLost = pst.executeQuery();
if (rsLost.next()) {
bLost = rsLost.getInt(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Table cannot be found");
}
// this is some stuff for the graph
DefaultCategoryDataset bagStats = new DefaultCategoryDataset();
// This should show me how many entries it found
bagStats.setValue(bLost, "Bagage Lost", "Bagage Lost");
The code works fine if i do the statement without the date part like this:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
I also tried using BETWEEN statements and it didn't work either.
I'm all out of ideas, I would really appreciate any help!
Caspar
You need to put quotes around the string in your sql code, so it reads as follows:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= \'" + strstartDate
+ "\' AND Datecreated <=\'" + strendDate + "\'");
Whenever constructing sql statements, it is a good idea to print the string statement on the command line or in a message box while debugging, so you can see exactly what is being passed.
Also, if accepting user input into a variable, it is good practice to parameterize the query in order to avoid the possibility of sql injection attacks.

Quick Help: converting SQL to LINQ

How do you convert this SQL to LINQ?
I'm reading it now, but just putting this out there in case I can't do it.
SqlConnection connection = new SqlConnection
{
ConnectionString = ConfigurationManager.ConnectionStrings["HBOS"].ConnectionString
};
connection.Open();
foreach (ExchangeRateData x in exchangeRateDatas.ExchangeRateDataList)
{
SqlCommand cmd = new SqlCommand("UPDATE dbo.CurrencyExchange " +
"SET Rate = '" + x.Rate + "', DateTimeStamp = CAST('" + x.TimeStamp +
"' AS DATETIME), CreatedBy = '" + x.CreatedBy + "', RateInv = '" +
x.RateInv + "' " +
"WHERE Currency = '" + x.ToCurrency + "';", connection);
// Sql query and connection
cmd.ExecuteNonQuery();
}
connection.Close();
Create a dbcontext first
then
CurrencyExchange CurrencyExchangeObject = context.CurrencyExchange
.Where(a => a.Currency = x.ToCurrency)
.FirstOrDefault();
after that you can simple assign the values
like
CurrencyExchangeObject.Rate = x.Rate;
CurrencyExchangeObject.DateTimeStamp = Convert.ToDateTime(x.TimeStamp);
and then simply say
context.SaveChanges();
Sounds like your boss is looking for a LINQ to SQL implementation. Unfortunately, your question does not have a quick answer because adding this functionality requires a lot more than just "converting a query to LINQ", as there are a number of things needed to get your environment set up to support it.
You may want to start with some basic Googling of the topic:
First couple results:
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
http://msdn.microsoft.com/en-us/library/bb386976(v=vs.110).aspx
LINQ to SQL has a more widely-used cousin called Entity Framework, which is not dependent upon SQL Server. You may want to consider that as well.

sqlite-net query with parameter that contains multi instructions

I have a table with lots of information and now I want that a user can search that table.
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
This is working and the solution I want to get to.
The problem is, that when the searchString is something like Dü, D' I get an exception.
I found here sqlite-net like statement crashes a good solution for the problem.
My problem is, that the only solution I found for now is something like:
if (words.Length < 2)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ?", "%" + words[0] + "%");
else if (words.Length < 3)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ? and Searchstring LIKE ?", "%" + words[0] + "%", "%" + words[1] + "%");
and so on......
but this is not the solution I want.
Someone got an Idea?
You need to replace the special characters that makes an error in SQL string
For example the ' character need to be replaced with '' in SQL string. So, we need to modify your code to be like that.
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word.Replace("'", "''") + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
To know more about how to escape special characters please refer to the following link
How does one escape special characters when writing SQL queries?
I cant offer advice about the issue where the accented "Du" is concerned, but D' causes an error because the ' isnt escaped, and it interferes with the sql; accordingly in your first code block,
replace
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
with
sqlSearch += " and Searchstring LIKE '%" + word.Replace("'","''") + "%'";
Here's another way of writing N.Nagy 's answer, with less string joins:
var words = (IEnumerable<string>)searchString.Split(' ').ToList();
const string SqlClause = "Searchstring LIKE '%{0}%'";
words = words.Select(word => string.Format(SqlClause, word.Replace("'", "''")));
var joined = string.Join(" AND ", words.ToArray());
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, joined));
Because everybody should know about string.Join()!!
And just for giggles:
const string SqlClause = "Searchstring LIKE '%{0}%'";
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, string.Join(" AND ", searchString.Split(' ').Select(word => string.Format(SqlClause, word.Replace("'", "''"))).ToArray())));
:)