Unable to frame sql query correctly from java - sql

I am trying to query data from my app, through postgresql DB. What I want to achieve is from "Users" where "Username"='stackoverflow'
If this query is written in the SQl editor and run, it gives the expected result.
Thus, am trying to send the query in the same format, as
String SQL_QUERY = "from " + "\"Users\"" + " where "
+ "Username" + "=" + "'"
+ request.getParameter("username") + "'";
When I run this, I get the following error:
unexpected char: '"' [from "Users" where Username=user1]
If I remove the double quotes, it wont work, saying table named users doesn't exist.
What is the way out of this deadlock? Where am I going wrong ??
Thank you.

This should be what you want:
String username = request.getParameter("username");
String SQL_QUERY = "SELECT * FROM \"Users\" WHERE \"Username\" ='" + username + "'";
You can check this by
System.out.println(SQL_QUERY);
which prints
SELECT * FROM "Users" WHERE "Username" ='foo'
ATTENTION/DANGER: This statement will solve your problem with the PostgreSQL mixed-case tablename and columnnames. BUT providing the value for Username to the query this way makes you vulnerable to even the easiest SQL-Injection attack. Please use PreparedStatement instead and write
String SQL_QUERY = "SELECT * FROM \"Users\" WHERE \"Username\" = ?";

Where's the SELECT clause of the query? It needs to be something like this:
String SQL_QUERY= "SELECT * FROM Users WHERE Username='" + request.getParameter("username") + "'";
Or like this:
String SQL_QUERY= "SELECT FirstName, LastName, Email FROM Users WHERE Username='" + request.getParameter("username") + "'";
Here's a very similar example that uses PreparedStatement to avoid a SQL injection security attack: https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java

Following the Postgresql syntax has in the end helped in getting a solution. Changed all the column names to small capitals and then tried, which solved most of the problems. Thanks to A.H
String SQL_QUERY = "FROM Users WHERE username ='" + username + "'";
Query query = objSession.createQuery(SQL_QUERY);
List list = query.list();
for (Iterator it = list.iterator(); it.hasNext();) {
Users objUsers = (Users) it.next();
System.out.println("Username: " + objUsers.userName);
System.out.println("Password: " + objUsers.password);
System.out.println("Name: " + objUsers.name);
}

Related

Query database and check not equal to

I have a data set in excel that I am querying info in a database using that data set. However, when checking against the database I get the "too few parameters. Expected 1" error.
Query:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Racf] = '" & sRacf & "') AND ([DateChecked] = #" & sDateChecked & "#) AND ([Overall] <> '" & sOverall & "') ;")
Literal:
SELECT * FROM [CallQuality] WHERE ([Racf] = 'SMITHJ') AND ([DateChecked] = #2017/05/17#) AND ([Overall] <> 'Development Required') ;
I have tried without the brackets and using != instead of <>. I am sure it is something simple I am missing.
Edit:
Error in this section:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Overall] <> '" & sOverall & "')")
Edit2:
The field name was wrong. Sorry guys! Not sure why it didnt give me the name error when it didnt find the field.
Thank you for your help.
use a + instead of & in the query.
So use this:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Racf] = '" + sRacf + "') AND ([DateChecked] = #" + sDateChecked + "#) AND ([Overall] <> '" + sOverall + "') ;");
If you look in the Error List you should get:
Error CS0019 Operator '&' cannot be applied to operands of type
'string' and 'string'
I can see why you put the & instead. Simple mistake :-)
It was an issue with the field name in the query.

VB6 SQL Type Mismatch issues with Databases

For my project, I have integrated a calculator which converts CM to FT. To make it worth more marks, I am trying to make it so that it will get the values and compare them against a Database to see which size Garage Door would be most suitable for the job
The SQL which purely searches for the value works. through and ADO which then only shows the found value on a data grid. But when I try to use the BETWEEN version, I get a Type Mismatch error which I have tried to fix by changing the variables to Integers and Reals, but it doesn't work. If anyone could help with this I would be really grateful!
Option Explicit
Dim sql As String
Dim sizeFindH As String
Dim sizeFindW As String
Dim sizeFindHUp As Double
Dim sizeFindHDown As Double
Dim sizeFindWUp As Double
Dim sizeFindWDown As Double
feet = 30.48
heightCm = txtHeightCm.Text
widthCm = txtWidthCm.Text
txtHeight.Text = heightCm / feet
txtWidth.Text = widthCm / feet
heightFt = txtHeight.Text
widthFt = txtWidth.Text
sizeFindH = txtHeight.Text
sizeFindW = txtWidth.Text
sizeFindHUp = sizeFindH + 1
sizeFindHDown = sizeFindH - 1
sizeFindWUp = sizeFindW + 1
sizeFindWDown = sizeFindW - 1
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.width) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
The error Type Mismatch highlights this line of code, as I'm sure it would the next if I could fix it.
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.width) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
The problem with your code in the SQL statement is that you are using an extra parentheses before the AND operator. It's not a logical operator here combining 2 conditions.. It's part of the BETWEEN clause and shouldn't have parentheses before. Also the % shouldn't be used here as others said.
Also the single quote is only used with strings.. So as long as your fields are numbers you shouldn't use it.
Oh.. And there's an extra parentheses without an opening one at the end of the query.
So your SQL should look like this:
sql = "SELECT * FROM garageDoorSize WHERE (garagedoorSize.width) BETWEEN " & sizeFindHDown & " AND " & sizeFindHUp & ";"
You are trying to concatenate a number and a string, hence the Type mismatch exception . Use CStr to convert the numbers to strings.
Also, I think you don't need the % signs, which are used with LIKE comparisons.
Also, as #jac correctly pointed out, use & to concatenate strings, not +. Edited my example to reflect for future readers of the post..
Try
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" & CStr(sizeFindHDown) & "') AND '" & CStr(sizeFindHUp) & "');"
Note: Your code style of adding values direct to sql strings is vulnerable to sql injection (although not in this case as they are numbers). If these were strings, and came from user input your database and application is not secure. Best practice is to us sql parameter objects for your values... See this post, which shows usage. Note, first post I found, sure there are better guides out there :)

Enterprise Architect - Execute SQL Issue

I'm getting the error "DAO.Database[3464] Data type mismatch in criteria expression." when attempting to update the t_connector table in Enterprise Architect by using the undocumented Execute command. Is what I'm trying to do not supported by EA's Execute SQL capabilities?
What I'm Doing
Note: This is within a loop so index is just an int. connector is an EA.Connector.
String addTrigger = "UPDATE t_connector SET PDATA1 = " + "'SAMPLE" + index + "'"
+ " WHERE Connector_ID = " + "'" + connector.ConnectorID + "';";
repository.Execute(addTrigger);
My Guess
I don't know SQL very well... did I mess up the statement somehow?
Further Information
A previous question I asked that lead me to what I'm doing now:
Add Trigger to Transition
Thanks #McAdam331 for your comment. Indeed, ConnectorID requires an int, not a string. Remove ' ' around connector.ConnectorID
String addTrigger = "UPDATE t_connector SET PDATA1 = " + "'SAMPLE" + index + "'"
+ " WHERE Connector_ID = " + connector.ConnectorID + ";";
repository.Execute(addTrigger);

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