Why does MySQL complain about an unknown column in this query? - java

I am getting following error while I try to use mysql query
Problem in Query
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'abc123' in 'where clause'
This is what I am using
public Student validate_Student(String s, String t) {
Student obj = new Student();
int w = Integer.parseInt(s);
String query = "SELECT s.* FROM student s JOIN login l on s.id = l.Student_ID WHERE l.Student_ID = " + w + " and l.Password= " + t;
try
{
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
obj.setID(rs.getString("ID"));
obj.setName(rs.getString("NAME"));
obj.setAddress(rs.getString("ADDRESS"));
obj.setPhone(rs.getString("PHONE_NO"));
obj.setEmail(rs.getString("EMAIL"));
obj.setDOB(rs.getString("DOB"));
obj.setDegree(rs.getString("DEGREE"));
}
}
catch(SQLException e)
{
System.out.println("Problem in Query");
e.printStackTrace();
}
}
return obj;
}

Try with replacing the following line.
String query = "SELECT s.* FROM student s JOIN login l on s.id = l.Student_ID WHERE l.Student_ID = " + w + " and l.Password = '" + t +"'";
UPDATE : You should use PrepareStatement instead of Statement in above example, which will help you to handle this kind of situations easily.
Also, there are more Advantages of Prepare Statement.
Prepare Statement Demo
I hope it helps.

Related

Java - Sql query with Alias

I want to retrieve a particular column from the database. For a simple Select statement, I can able to able to retrieve a column like below
public String getDbColumnValue(String tableName, String columnName, String applicationNumber) {
String columnValue = null;
try {
PreparedStatement ps = null;
String query = "SELECT " + columnName + " FROM " + tableName +
" WHERE ApplicationNumber = ?;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString(columnName);
return columnValue;
}
}
catch (Exception ex) {
}
return columnValue;
}
But, I'm using alias in my query like below. And this query works fine. How to use this in Java to retrieve a particular column
select S.StatusDesc from application A, StatusMaster S
where A.StatusMasterId = S.StatusMasterId and A.ApplicationNumber = '100041702404'
Any help would be greatly appreciated!
I think you are confusing simple aliases, which are used for table names, with the aliases used for column names. To solve your problem, you can just alias each column you want to select with a unique name, i.e. use this query:
select S.StatusDesc as sc
from application A
inner join StatusMaster S
on A.StatusMasterId = S.StatusMasterId and
A.ApplicationNumber = '100041702404'
Then use the following code and look for your aliased column sc in the result set.
PreparedStatement ps = null;
String query = "select S.StatusDesc as sc ";
query += "from application A ";
query += "inner join StatusMaster S ";
query += "on A.StatusMasterId = S.StatusMasterId ";
query += "and A.ApplicationNumber = ?";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString("sc");
return columnValue;
}
Note: I refactored your query to use an explicit inner join instead of joining using the where clause. This is usually considered the better way to write a query.

Java SQLite Select Query

I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again

Error: Incorrect syntax near (database name)

hi I am getting this error in my Java program. Here is my query. It is working good in SQL server. but getting
Error: Incorrect syntax near 'WebApp'.
private static final String SERVICES =
"SELECT s.Service_ID "
+ ",s.[Location_ID] "
+ ",COALESCE(st.[Service_Type_Name],s.[Service_Name]) AS Service_name "
+ ",st.Service_Type_Name "
+ " FROM [WebApp].[dbo].[Services] s join [WebApp].[dbo].[ServiceTypes] st on s.Service_Type=st.Service_Type_ID "
+ " join WebApp.dbo.Locations l on s.Location_ID=l.Location_ID "
+ " where s.Deleted=0 "
+ " ORDER BY Location_ID ";
and here is my method it is working fine on ms sql server 2008
public List<MAServiceVO> getAddServices() throws CoopCRSAPIException {
ArrayList<MAServiceVO> results = new ArrayList<MAServiceVO>();
MAServiceVO maServiceVO = null;
log.debug("==========IN VendorDAOimpl.java (service)===========");
//int serviceID = 0;
//int prevServiceID = 0;
try {
conn = MSSQLDAOFactory.createConnection();
stmt = conn.prepareStatement(SERVICES);
// stmt.setTimestamp(1, startDate);
// stmt.setTimestamp(2, endDate);
stmt.execute();
rs = stmt.getResultSet();
while (rs.next()) {
// create new service
maServiceVO = new MAServiceVO();
// set service fields
maServiceVO.setServiceID(rs.getInt("Service_ID"));
maServiceVO.setLocationID(rs.getInt("Location_ID"));
maServiceVO.setServiceName(rs.getString("Service_Name"));
maServiceVO.setServiceType(rs.getString("Service_Type_Name"));
log.debug("==========done with VendorDAOimpl.java (service)===========");
}
} catch (SQLException e) {
log.debug(e.getMessage());
throw new CoopCRSAPIException(e.getMessage(), " VendorDAOimpl", "getAddServices", 500);
} finally {
closeConnections("getAddServices");
}
log.debug("&&&&&&&&&&&&&&&&&&&&&");
log.debug("==========finsh===========");
return results;
}
I don't see anything out of whack there. If there a reason you don't have this in a stored procedure instead of pass through sql? I did notice you didn't put square brackets around your final join but that shouldn't make any difference.
Here is your query after stripping off all the extra string parts for java.
SELECT s.Service_ID
, s.[Location_ID]
, COALESCE(st.[Service_Type_Name], s.[Service_Name]) AS Service_name
, st.Service_Type_Name
FROM [WebApp].[dbo].[Services] s
join [WebApp].[dbo].[ServiceTypes] st on s.Service_Type = st.Service_Type_ID
join [WebApp].[dbo].[Locations] l on s.Location_ID = l.Location_ID
where s.Deleted = 0
ORDER BY Location_ID;

Suddenly getting SQL Exceptions when using sql variables in statements

I have a SQL query, consisting of different statements (this is a simplified version, which also triggers the error) :
private static String getActiveKeyEventsSql =
"SET #report_model_id = 2; " +
"SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
I am trying to call that statement from inside my Java Application:
public static void main(String[] args) throws Exception {
MySQLLayer _db = new MySQLLayer();
Connection _conn = null;
try {
_conn = _db.getConnection();
PreparedStatement getActiveKeyEventsStmt = _conn.prepareStatement(getActiveKeyEventsSql);
ResultSet rs = getActiveKeyEventsStmt.executeQuery();
while (rs.next()) {
LOG.info(rs.getLong("report_ts"));
}
} catch (SQLException e) {
LOG.error("COULD NOT GET MAX REPORT.", e);
} finally {
try {
if (_conn != null && !_conn.isClosed()) {
_conn.close();
}
} catch (SQLException e) {
LOG.info("COULD NOT CLOSE CONNECTION.", e);
}
}
}
But it triggers the following error:
java.sql.SQLException: ResultSet is from UPDATE. No Data.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6870)
at com.stockpulse.stockstorm.sentiment.JavaTest.main(JavaTest.java:36)
In other places of my application, this schema works just fine. When I copy this statement to the MySQL console, it works just fine.
Here is the String to init the DB:
config.setJdbcUrl(
"jdbc:mysql://" + cred.getHOST() + "/" + cred.getDB()
+ "?allowMultiQueries=true&characterEncoding=utf-8&useUnicode=true&rewriteBatchedStatements=true&relaxAutoCommit=true"
);
Why is JDBC behaving this way out of the sudden?
Try breaking your statement into
a = "SET #report_model_id = 2; ";
b = "SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
And do PreparedStatement.addBatch() for each.

select same value from N rows in a mysql database

I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.
You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it

Categories