SQL entries not showing in graph - sql

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.

Related

Is it possible to read data from multiple data sources in SSIS whose connection strings are saved in SQL table?

Connection strings for each data source, i.e Excel, OLE DB etc. are saved in an SQL table. We need to pull each connection string at a time and then read the corresponding data source(Flat file, excel, OLE DB), check the number of records and load the same in destination SQL table.Though I tried foreach loop container in SSIS, but it worked for OLEDB, not working for Excel, flat file.
try
{
int IsActive = Convert.ToInt32(Dts.Variables["User::IsActive"].Value);
String Table = Dts.Variables["User::SourceTable"].Value.ToString();
String ConnString = Dts.Variables["User::ConnString"].Value.ToString();
if (IsActive == 1)
{
string SQL = "SELECT '" + Table + "' AS TableName, N'" + ConnString + "' AS ConnString, COUNT (*) AS RecordCount, GETDATE() AS ActionTime FROM " + Dts.Variables["User::SourceTable"].Value.ToString() + " (NOLOCK)";
Dts.Variables["User::Query"].Value = SQL;
Dts.TaskResult = (int)ScriptResults.Success;
}
}
catch (Exception ex)
{
;
}

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.

Error with SQL command

I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
However I think that the problem is actually coming from this section:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)
You should use parameterized query and all of this will disappear
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("#p1", txtSSN.Text);
command.Parameters.AddWithValue("#p2", txtName.Text );
command.Parameters.AddWithValue("#p3", txtCompany.Text);
command.Parameters.AddWithValue("#p4", _UserID);
command.ExecuteNonQuery();
Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection

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

help me with the following sql query

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