java derby database query, with user input text - java

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

Related

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.

No such Table Sqlite JDBC

Yo guys. The problem I'm facing is pretty weird..
I am creating a table at first, then trying to put data on it, but for somereason something is ticking off. It says
[SQLITE_ERROR] SQL error or missing database (no such table: Name)
Aaand here's my basic code..
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
stmt = conni.createStatement();
String sql = "CREATE TABLE " + project.getText() + " (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , Name TEXT, One TEXT, Two TEXT)";
stmt.executeUpdate(sql);
stmt.close();
conni.close();
}catch (Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into Name (Name) values(?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into " + project.getText() + "(Name, One, Two) values(?,?,?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.setString(2, textField_one.getText());
pst.setString(3, textFieldtwo.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
JOptionPane.showMessageDialog(null, "Thank you");
Thank you for the help! I really can understand... I guess the table is not being created at all, but it actually worked once. So It gets me even more confused o.o
Name is a MySql reserved keyword. Rename the table to something else.
Please encase your fieldnames with " to escape them.
String sql = "CREATE TABLE \"" + project.getText() + "\" (\"Id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"Name\" TEXT, \"One\" TEXT, \"Two\" TEXT)";
String query1 = "insert into \"Name\" (\"Name\") values(?)";
String query1 = "insert into \"" + project.getText() + "\" (\"Name\", \"One\", \"Two\") values(?,?,?)";
Also... I'm assuming you've patched together these code snippets from various points in your code..
But i advice you to set up a SINGULAR database connection in your code and to reuse that connection throughout your application.
Something along the lines of:
public class MyApp {
public static Connection DB;
public void initDatabase() {
try {
MyApp.DB = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
}
catch(Exception ex) {
}
}
public static void main(String args[]) {
MyApp app = new MyApp();
app.initDatabase();
}
}

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;

Connection from Java Application and Stored Procedure MSSQL

I have the stored procedure in SQL Sever and it has a few parameter. I would like to give the value of parameter from the combo box (in java application). I've read this code (look at below)
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But i didn't get the meaning. Is there any tutorial that give me some example just like in my case? Thanks for any reply
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
1) Line 1 creates a prepare statement object with your Stored Procedure. The ? is the placeholder for the input parameter to the Stored Procs
2) Line 2 sets the input param to the stored proc
3) executeQuery executes the stored proc by providing the input and get the output as a resultset.
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
Above lines iterate over the result set and print each record
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");//Creating a prepared statement with the string to execute your procedure.
pstmt.setInt(1, 50);//This is to set the parameter to the place holder '?'
ResultSet rs = pstmt.executeQuery();//This is to execute your procedure and put the result into a table like set
while (rs.next()) {//To check if there are any values in the set, if so the print those values
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();//close the set
pstmt.close();//close the statement
}
catch (Exception e) {
e.printStackTrace();
}
}

Data does not get inserted into the table sometime

I have a table A. I insert data into table A through a user interface. Table A has an ID(primary key), which is generated using a sequence, and 16 other columns. One of the column is called cntrct_no.
When I try to insert data into the table through UI, it works fine the first time. I check the table A and all the data are there.
But when I try to insert the same data again without changing anything, it looks like the data is getting added to the table and I do not get any errors. But when I check table A, the data inserted the second time is not there.
If I try to insert the same data directly thorough SQL developer, the data gets inserted into the table.
The weird thing is if I just change the value of the cntrct_no in the UI and leave rest of the data same, the data gets inserted.
Can anyone please explain to me what could possibly cause this?
Not sure if this helps: stmt.executeUpdate(); returns 0 when the data is not inserted and a 1 when it's inserted.
public void writeToAudit(String contractNo, String tripNo,
String tripEffDate,
String tripDiscDate, String transpModeId, String userId,
String transType, AplLeg[] legs) {
final Session session = HibernateUtil.getSession();
Connection con = null;
con = session.connection();
PreparedStatement stmt = null;
PreparedStatement stmtSelId = null;
ResultSet rs = null;
long nextId = -1;
int i=0;
try {
for(i=0;i<legs.length;i++) {
String sqlNextId = "SELECT rpt_audit_transportation_seq.NEXTVAL as seqval FROM DUAL";
stmtSelId = con.prepareStatement(sqlNextId, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmtSelId.executeQuery();
rs.last();
final int rows = rs.getRow();
if (rows == 0){
nextId = -1;
}
rs.beforeFirst();
rs.next();
nextId = rs.getInt(1);
if(nextId==-1)
throw new SQLException("Cannot get next val from rpt_audit_transportation sequence.");
stmt = con.prepareStatement(WRITE_TO_AUDIT_DML);
stmt.setLong(1, nextId);
stmt.setString(2, userId.toUpperCase());
stmt.setString(3, transType);
stmt.setString(4, contractNo);
stmt.setString(5, tripNo);
stmt.setInt(6, Integer.parseInt(transpModeId));
stmt.setString(7, tripEffDate);
stmt.setString(8, tripDiscDate);
stmt.setLong(9, legs[i].getLegId().longValue());
int temp = stmt.executeUpdate();
con.commit();
}
stmt.close();
}
catch (Exception e) {
}
finally {
closeConnection(session, con, stmtSelId, rs);
}
}
THE SQL STATEMENT:
private static final String WRITE_TO_AUDIT_DML =
"INSERT INTO rpt_audit_transportation " +
"(audit_id, audit_date, audit_process, audit_userid, " +
"audit_trans_type, audit_route_no, audit_trip_no, " +
"audit_eff_dt, audit_disc_dt, audit_orig_facility_id, " +
"audit_dest_facility_id, audit_arvl_tm, audit_dprt_tm, " +
"audit_leg_seq_no, audit_freq_id, audit_trnsp_mode_id) " +
"(SELECT ?, " + // audit id
"SYSDATE, " +
"'TOPS_UI', " +
"?, " + // userId
"?, " +
"rte.cntrct_no, " +
"trp.trip_no, " +
"rte.cntrct_eff_dt, " +
"rte.cntrct_disc_dt, " +
"NVL(leg.orig_facility_id, trp.orig_fac_id), " +
"NVL(leg.dest_facility_id, trp.dest_fac_id), " +
"NVL(leg.arvl_tm, trp.arvl_tm), " +
"NVL(leg.dprt_tm, trp.dprt_tm), " +
"leg.leg_seq, " +
"trp.freq_id, " +
"rte.trnsp_mode_id " +
"FROM apl_contract rte, " +
"apl_trip trp, " +
"apl_leg leg " +
"WHERE rte.cntrct_no = ? " + // contract id
"AND trp.trip_no = ? " + // trip no
"AND rte.trnsp_mode_id = ? " + // transp mode id
"AND rte.cntrct_locked_ind = 'N' " +
"AND trp.trip_eff_dt = to_date(?,'MM/DD/YYYY') " + // trip eff date
"AND trp.trip_disc_dt = to_date(?,'MM/DD/YYYY') " + // trip disc date
"AND trp.cntrct_id = rte.cntrct_id " +
"AND leg.trip_id = trp.trip_id " +
"AND leg.leg_id = ?) ";
Looks like you're not inserting plain values, but a result of a select based on the parameters.
What you are using is an INSERT ... SELECT () clause, so if the SELECT part does not return any rows, the INSERT won't insert anything, and stmt.executeUpdate() will return 0. Find out why SELECT returns no rows.
This may be due some triggers saving stuff in other tables when you do the insert into rpt_audit_transportation, but it's just a guess.
The problem is that you have a catch that is swallowing your exceptions
catch (Exception e) {
}
That means that when the SQL statement throws an error, you're telling your code to catch the exception and ignore it. It is almost always an error to do that since, as you're discovering, it means that your code can fail to do what you expect with no way of letting you know that something failed. At a minimum, you would need to log the exception somewhere. In general, though, if you cannot fix whatever condition lead to the exception, you ought to re-raise the exception or simply not catch it in the first place.
My guess is that the second insert is violating some constraint defined on the table. But since your code is catching the exception and throwing it away, you're not being notified that there was a constraint violation nor is your code noting which constraint was violated.
When the cntrct_no is same you are getting an exception and you are supperessing that as told by #Justin Cave. This may be because you are having a unique constraint for that field and the DB throws an error and you are suppressing.
When cntrct_no is changed - obviously the constraint wont fail and for primary key since you are using the sequence it would have generated the next number and it happily gets inserted in the DB.
Don't ever suppress the exception. Do some thing in that block either rethrow as application specific exception or convert to error code and propagate that to the front end.

Categories