Error: Incorrect syntax near (database name) - java

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;

Related

SQL parameter issue Jdbc

I am taking input from user and storing in two different variables. I am binding the parameters with my sql statement. When i run the code its giving issue on concatenating part of query.
String CityA= null;
String CityB= null;
try {
CityA = readEntry(in, "Enter Origin City : ");
CityB = readEntry(in, "Enter Destination City : ");
// We treat this drop table specially to allow it to fail
// as it will the very first time we run this program
try {
String q = "SELECT f.FLNO,f.DISTANCE,TIMEDIFF(f.arrives,f.departs)
as Duration FROM FLIGHTS F"
+ " WHERE F.ORIGIN = "+CityA;
+ "AND f.DESTINATION = "+CityB;
System.out.println(q);
rset = stmt.executeQuery(q);
while (rset.next()) {
System.out.println(rset.getInt("FLNO") + ","
+ rset.getInt("Distance") + ","
+ rset.getTime("Duration"));
}
System.out.println("Done");
}
catch (SQLException e) {
// assume not there yet, so OK to continue
}
finally {
stmt.close();
}
Please find the code for query:-
Basically you missed the space between the CityA and AND
String q = "SELECT f.FLNO,f.DISTANCE,TIMEDIFF(f.arrives,f.departs) as Duration FROM FLIGHTS F"
+ " WHERE F.ORIGIN = '"+CityA+"' ";
+ "AND f.DESTINATION = '"+CityB+"'";
There is a typo in your query string - you missed the space between 'Los-Angeles' and AND.

ORA-00923: FROM keyword not found where expected in SeleniumWebDriver

I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}
3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.

java derby database query, with user input text

I have a java derby database, I can write to and read from the database.
I am having trouble:
Making it so that the text that the user enters into the text field, is then incorporated into the database query to determine the results displayed.
I tried it this way, the results were, if I click the search button, it will return the info/query into the "run" screen, not actually incorporating the user input into the query tho, I have to do that in the code, by replacing the abc to the number in the database.
Do I have to create some kind of command line argument? set the variable differently? Can I just replace the query info where the database info goes with a variable like how I tried in the upcoming example?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String abc = jTextField1.getText();
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "app");
Statement st = conn.createStatement()) {
Class.forName("org.apache.derby.jdbc.ClientDriver");
ResultSet rec = st.executeQuery(
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 "
+ "where (ROW4 = 'abc')");
while (rec.next()) {
System.out.println("ROW1:\t"
+ rec.getString(1));
System.out.println("ROW2:\t" + rec.getString(2));
System.out.println("ROW3:\t" + rec.getString(3));
System.out.println("ROW4:\t" + rec.getString(4));
System.out.println("ROW5:\t" + rec.getString(5));
System.out.println();
}
st.close();
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString()
+ e.getMessage());
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
You are not setting the variable correctly. Instead of setting the ROW4 to 'abc' you need to set the variable. Try this.
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 " + "where (ROW4 = '"+abc+"')"
Its always better to use preparedStatement. this will avoid lot of problem related to SQL Injection.
String selectSQL = "select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 where ROW4 = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, abc);
ResultSet rs = preparedStatement.executeQuery(selectSQL );

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

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.

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.

Categories