I am trying to make a simple JSP snippet to perform queries on an oracle database and display results. Query can be anything like select, delete, alter, update, etc. I need help with making a general code to display query results and errors.
Here is what I have coded so far:
<%# page language="java" import="java.sql.*" %>
<%#page import="oracle.jdbc.driver.*" %>
<%#page import="oracle.sql.*;" %>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:thin:#192.168.0.22:1521:orcl",
"test", "testpass");
stmt = conn.createStatement();
String que = request.getParameter("q");
rset = stmt.executeQuery (que);
} catch (SQLException e) {
out.println("<P> SQL error: <PRE> " + e + " </PRE> </P>\n");
} finally {
if (rset!= null) rset.close();
if (stmt!= null) stmt.close();
if (conn!= null) conn.close();
}
%>
My questions are:
How can I automatically display all columns and rows when I execute a query like "select * from emp".
How to check if a delete/update query has worked correctly or not.
How to view and alter oracle triggers using JSP.
1.Use ResuletSetMetaData
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE","scott","tiger");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
if( rs.next()){
// print column names
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i=1; i<= columnCount; i++)
System.out.print(rsmd.getColumnName(i) + "\t");
System.out.println();
// print rows
do {
for( int i=1; i<=columnCount; i++)
System.out.print( rs.getString(i) + "\t");
System.out.println();
} while(rs.next());
}
conn.close();
2.Statement's executeUpdate() method return affected rows as int.
3 (a). Create trigger
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE","scott","tiger");
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE OR REPLACE TRIGGER yourtrigger BEFORE DELETE ON emp FOR EACH ROW BEGIN dbms_output.put_line('row deleted..'); END;");
conn.close();
3 (b). View trigger
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE","scott","tiger");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select text from user_source where name = 'YOURTRIGGER'");
if( rs.next())
System.out.println(rs.getString(1));
conn.close();
Related
I'm running java 1.8 connecting to oracle 12c using ojdbc7.jar for jdbc connection.
This is the code that execute to retrieve the data
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt=con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
but the code is not entering the while loop.
When i try exeuction the same query in DB, I could see the table has 10 entries.
Does anyone know what could be the reason?
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt = con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e ) {
} finally {
if (stmt != null) { stmt.close(); }
}
I have 2 queries and therefore 2 ResultSet's returned from MySQL in Java through createStatement(). The queries are like
SELECT * FROM abc;
SELECT * FROM def;
These queries are run simultaneously in single createStatement() like
CreateConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
stat.close();
conn.close();
How can I get the next ResultSet returned by second query?
Use Statement#getMoreResults and Statement#getResultSet methods:
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
if (stat.getMoreResults()) {
rs = stat.getResultSet();
while(rs.next()) {
//Iterate through second resultset
}
}
stat.close();
In order that make this method to work, you should add allowMultiQueries=true property to your connection by appending this property to your connection url:
String url = "jdbc:mysql://yourServer:yourPort/yourDatabase?allowMultiQueries=true";
Note that you can perform multiple queries per Statement using a single Connection object:
Connection con = ...
List<String> sqlStatements = ... //a list with all the SELECT statements you have
for (String query : sqlStatements) {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//do your logic here...
}
rs.close();
stmt.close();
}
conn.close();
I am getting this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
public static Person getDetails(int id) {
Connection conn = null;
PreparedStatement stmt = null;
Person newPerson = new Person();
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "SELECT firstName, lastName, birthday FROM person WHERE id=?";
System.out.println("SQL Statement:\n\t" + stmt);
stmt = conn.prepareStatement(sql);
System.out.println("Prepared Statement before bind variables set:\n\t" + stmt.toString());
//Bind values into the parameters.
System.out.println("ID " + id);
stmt.setInt(1, id); // This would set id
System.out.println("Prepared Statement after bind variables set:\n\t" + stmt.toString());
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
Date birthday = rs.getDate("birthday");
newPerson.setBirthday(birthday);
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setId(id);
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + firstName);
System.out.println(", Last: " + lastName);
System.out.println(", Birthday: " + birthday);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
return newPerson;
}
I have success executing the query without the where clause. I have looked at many examples and nothing I try fixes this.
Don't use executeQuery(String) with prepared statements...
Instead of....
ResultSet rs = stmt.executeQuery(sql);
use...
ResultSet rs = stmt.executeQuery();
Take a look at How to use Prepared Statements for more details
If I understand your question, the problem is you used Statement.executeQuery(String). I'm fairly certain you meant to use PreparedStatement.executeQuery(),
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql); // <-- adding sql here makes it use the
// Statement version.
You wanted to use
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(); // <-- use the version from PreparedStatement
Change
ResultSet rs = stmt.executeQuery(sql);
to
ResultSet rs = stmt.executeQuery();
I was trying to call a method in jsp which returns a resultSet. Like,
In JSP:
OracleResultSet rs = null;
rs = getMyValuesHere();
out.println("rs:"+rs);
// rs is not null.Something like oracle.jdbc.driver.OracleResultSetImpl#1f1e1f
How can I retrieve my values here from the resultSet?
because not even entering into this while loop. ,
while(rs.next()) {
}
Method is:
<%!
public OracleResultSet getMyValuesHere()
{
OracleConnection connection = null;
OraclePreparedStatement ptmst = null;
OracleResultSet rs = null;
OracleCallableStatement cstmt = null;
StringBuffer sql = new StringBuffer();
//My query goes here
connection = (OracleConnection) TransactionScope.getConnection();
sql.append("SELECT DISTINCT something.... ");
rs = (OracleResultSet)ptmst.executeQuery();
return rs;
}
%>
I tried printing the data in getMyValuesHere()
rs = (OracleResultSet)ptmst.executeQuery();
while (rs.next())
{
// rs.getString(1)) -- I was able to print this.
}
You didn't specified the Database Driver in your program.. Include the driver in your program and then try it once
I want to change the position of the cursor to the first row but I don't know why my code is not working.when I add rs2.first():
and also I am getting this error :
This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).
try{
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
String url = "jdbc:derby://localhost:1527/test";
Connection conn = DriverManager.getConnection(url);
String query = "select * from APP.RANKING";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query);
while (rs.next()){
String BID = rs.getString("BALLOT_ID");
String CN = rs.getString("CANDIDATE_NAME");
String ROID = rs.getString("USER_ID");
Ro1_ID = ROID;
String RA = rs.getString("RANK");
int rowNum = rs.getRow();
int rowNum2;
boolean In_check = false;
while(rs2.next()){
In_ballot.addElement(BID);
}
rs2.First();
In_ballot.addElement(BID);
}
}
catch(Throwable e) {
System.err.println(e.getMessage());
}
this.InB_list.setModel(In_ballot);
By default, calling createStament() in a connection results in every ResultSet having type 'TYPE_FORWARD_ONLY' - This results in the exception you see using first().
Instead, use another versions of createStatement, like this one.
This sample of creating scrollable ResultSets in Derby might help.