Syntax Error when the column name contains underscore - sql

I can compile but can't execute the following code
with the error (using Postgres):
Fatal database error
ERROR: syntax error at or near "as"
Position: 13
import java.sql.*;
public class JDBCExample
{
private static final String JDBC_DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://hostname/database";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public static void main(String[] args) throws Exception
{
Connection dbConn = null;
Statement query = null;
ResultSet results = null;
Class.forName(JDBC_DRIVER);
try
{
dbConn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
catch (SQLException e)
{
System.out.println("Unable to connect to database\n"+e.getMessage());
System.exit(1);
}
try
{
query = dbConn.createStatement();
results = query.executeQuery("select 20_5 as name from flowshop_optimums");
while (results.next())
{
System.out.println(results.getString("name"));
}
dbConn.close();
}
catch (SQLException e)
{
System.out.println("Fatal database error\n"+e.getMessage());
try
{
dbConn.close();
}
catch (SQLException x) {}
System.exit(1);
}
} // main
} // Example

It's not the underscore, it's the fact that the column name starts with a number. You'd need to escape this.
For MySQL, use backticks.
select `20_5` as name from flowshop_optimums
For SQL Server, use square brackets.
select [20_5] as name from flowshop_optimums
For PostgreSQL, use double quotes.
select "20_5" as name from flowshop_optimums

results = query.executeQuery("select \"20_5\" as name from flowshop_optimums");
But you should really change that column name.

Try this: results = query.executeQuery("select '20_5' as name from flowshop_optimums");

You need to enclose 20_5 with backticks or brackets, depending on whether or not you're using MySQL or SQLServer, respectively.

Related

ArrayIndexOutOfBoundsException when performing resultSet.next() when there are more rows

I am trying to query a table that has long-raw() type data which is having a text in it. I need to export this data to a flat file. For a given id, I see there are 14 rows in the table. I am fetching the data using JDBC connection and when fetching the data using ResultSet, I am getting ArrayIndexOutOfBoundsException at 13th row. Not sure why this issue occurs.
The data in the long raw column could be large. I am suspecting it is not able to fetch all the data that is present. I might be wrong too. I cant find much information when could a ArrayIndexOutOfBoundsException occur in this scenario. Complete code is below-
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
public class TestMain {
private static String URL = "jdbc:oracle:thin:#localhost:8080:xe";
private static String USER_NAME = "scott";
private static String PASSWORD = "tiger";
public static void main(String[] args) throws SQLException, IOException {
Connection newConnection = getNewConnection();
BufferedWriter bw = new BufferedWriter(new FileWriter("./extractedFile/RawDataFile.txt"));
PreparedStatement extractableRowCount = getExtractableRowCount(newConnection, (long)34212);
ResultSet foundCountRs = extractableRowCount.executeQuery();
foundCountRs.next();
int foundCount = foundCountRs.getInt(1);
//`here I get 14 as the count`
System.out.println("Available rows for id:: 34212 are "+foundCount);
foundCountRs.close();
extractableRowCount.close();
PreparedStatement fetchBinaryQueryStatement = getExtractableRow(newConnection, (long)34212);
ResultSet fetchedRowsRs = fetchBinaryQueryStatement.executeQuery();
int i=0;
while (fetchedRowsRs.next()) {
i++;
//`I see outputs upto i=13, and then I get ArrayIndexOutOfBoundsException
System.out.println("i = " + i);
String userName = fetchedRowsRs.getString("user_name");
InputStream savedTextData = fetchedRowsRs.getBinaryStream("saved_text");
bw.write(userName + ":: ");
int len = 0;
if (savedTextData != null) {
while ((len = savedTextData.read()) != -1) {
bw.write((char) len);
bw.flush();
}
}
fetchedRowsRs.close();
fetchBinaryQueryStatement.close();
}
bw.close();
}
public static Connection getNewConnection() throws SQLException {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
return DriverManager.getConnection(URL, USER_NAME, PASSWORD);
}
public static PreparedStatement getExtractableRow(Connection connection, Long id) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SELECT user_name, saved_text FROM user_email_text_data where id = ?");
statement.setLong(1, id);
return statement;
}
public static PreparedStatement getExtractableRowCount(Connection connection, Long id) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SELECT count(1) FROM user_email_text_data where id = ?");
statement.setLong(1, id);
return statement;
}
}
Full stack trace of error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at oracle.jdbc.driver.T4CMAREngineNIO.buffer2Value(T4CMAREngineNIO.java:814)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB2(T4CMAREngineNIO.java:577)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalSB2(T4CMAREngineNIO.java:557)
at oracle.jdbc.driver.T4CMAREngine.processIndicator(T4CMAREngine.java:1573)
at oracle.jdbc.driver.T4CMarshaller$StreamMarshaller.unmarshalOneRow(T4CMarshaller.java:179)
at oracle.jdbc.driver.T4CLongRawAccessor.unmarshalOneRow(T4CLongRawAccessor.java:159)
at oracle.jdbc.driver.T4CTTIrxd.unmarshal(T4CTTIrxd.java:1526)
at oracle.jdbc.driver.T4CTTIrxd.unmarshal(T4CTTIrxd.java:1289)
at oracle.jdbc.driver.T4C8Oall.readRXD(T4C8Oall.java:850)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:543)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1023)
at oracle.jdbc.driver.OracleStatement.fetchMoreRows(OracleStatement.java:3353)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.fetchMoreRows(InsensitiveScrollableResultSet.java:736)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.absoluteInternal(InsensitiveScrollableResultSet.java:692)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.next(InsensitiveScrollableResultSet.java:406)
I was getting the exact same exception when calling ResultSet.next() using ojdbc8-12.2.0.1:
java.lang.ArrayIndexOutOfBoundsException: 8
at oracle.jdbc.driver.T4CMAREngineNIO.buffer2Value(T4CMAREngineNIO.java:814)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB2(T4CMAREngineNIO.java:577)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalSB2(T4CMAREngineNIO.java:557)
at oracle.jdbc.driver.T4CMAREngine.processIndicator(T4CMAREngine.java:1573)
at oracle.jdbc.driver.T4CMarshaller$StreamMarshaller.unmarshalOneRow(T4CMarshaller.java:179)
at oracle.jdbc.driver.T4CLongRawAccessor.unmarshalOneRow(T4CLongRawAccessor.java:159)
at oracle.jdbc.driver.T4CTTIrxd.unmarshal(T4CTTIrxd.java:1526)
at oracle.jdbc.driver.T4CTTIrxd.unmarshal(T4CTTIrxd.java:1289)
at oracle.jdbc.driver.T4C8Oall.readRXD(T4C8Oall.java:850)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:543)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1023)
at oracle.jdbc.driver.OracleStatement.fetchMoreRows(OracleStatement.java:3353)
The exception disappeared when I upgraded driver version to ojdbc8-18.3.0.0.
Updating JDBC driver might be worth a try, if anyone should find themselves in the same situation.
The below lines are at the end of the outer while loop but they need to be executed after the loop since you can't close the result set object and then call next()
fetchedRowsRs.close();
fetchBinaryQueryStatement.close();
As your size of array is 14 therefore the last index is 13 as it starts from 0.So you are accessing value of index greater than size of array it gives ArrayOutOfBound exception.

data provider mismatch error

I am using below code for data provider but it's not working. Please help to me how to resolve data provider mismatch issue. here mentioned complete details about all the methods reading xls , test , data provider .
#DataProvider
public Object[][] getgbTestData(){
Object data[][] = testutil.getTestData(sheetName);
return data;
}
#Test(dataProvider="getgbTestData")
public void addnewuser(String fname,String lname,String email,String pass,String conpass) throws IOException{
newuser.newregistration1(fname, lname, email, pass, conpass);
}
**method:**
public Personaldetails newregistration1(String fsname,String lsname,String email1,String pass1,String conpass1) throws IOException {
Account.click();
Registerlink.click();
Firstname.sendKeys(fsname);
Lastname.sendKeys(lsname);
useremail.sendKeys(email1);
password.sendKeys(pass1);
confirmpassword.sendKeys(conpass1);
submit.click();
//return person;
return new Personaldetails();
}
//using below method to read data from excel
public static Object[][] getTestData(String sheetName) {
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
// System.out.println(sheet.getLastRowNum() + "--------" +
// sheet.getRow(0).getLastCellNum());
for (int i = 0; i < sheet.getLastRowNum(); i++) {
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
// System.out.println(data[i][k]);
}
}
return data;
}
Looks like the test has required 5 arguments but your data provider method getTestData passing less/greater no of arguments.
You are passing the wrong number of arguments. The method addnewuser() expects 5 arguments, but receives only one. You can see it in the last line in the error message
Arguments: [(java.lang.String)fname]
If you want to pass different number of parameters you can use String[] instead of single arguments. And if you expect 5 arguments each time check what data holds in getTestData()

Inserting Error

I'm trying to insert in postgresql db date, but when I'm inserting it, I'm getting this error:
Error occurred while INSERTING operation: org.postgresql.util.PSQLException: ERROR: column "text that i wrote" does not exist"
I don't understand what did I code wrong that, program tries to find column in values?
But when I try to output this table, it outputs without errors
WORKERDAO class
public static void insertWrk(String name, String post) throws SQLException, ClassNotFoundException {
//Declare a INSTERT statement
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
//Execute INSTERT operation
try {
DBUtil.dbExecuteUpdate(updateStmt);
} catch (SQLException e) {
System.out.print("Error occurred while INSTERING Operation: " + e);
throw e;
}
}
DBUTIL class
public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
//Declare statement as null
Statement stmt = null;
try {
//Connect to DB
dbConnect();
//Create Statement
stmt = conn.createStatement();
//Run executeUpdate operation with given sql statement
stmt.executeUpdate(sqlStmt);
} catch (SQLException e) {
System.out.println("Проблема в выполнение executeUpdate операции : " + e);
throw e;
} finally {
if (stmt != null) {
//Close statement
stmt.close();
}
//Close connection
dbDisconnect();
}
}
WorkerController Class
#FXML
private void insertWorker (ActionEvent actionEvent) throws SQLException, ClassNotFoundException {
try {
WorkerDAO.insertWrk(nameText.getText(),postCombo.getSelectionModel().getSelectedItem());
} catch (SQLException e) {
System.out.println("Problem occurred while inserting worker " + e);
throw e;
}
}
You need to put quotes around the data you're inserting:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
Should be:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"('"+name+"',"'+post+'");";
Be aware that you're risking SQL Injection attacks using this method, see about using a parameterised insert. This site lists a bit more detail.

ResultSet is getting closed on executing statement.execute(sql)

On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)
you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()

SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.