JAVA- JDBC- ORACLE Connection issues - java

Using standard JDBC code for JAVA-ORACLE connection however not working.
This may be asked earlier but i am not able to debug it myself so asking here.
Request for help.
Code:
import java.sql.*;
class OracleCon {
public static void main(String args[]) {
try {
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// step2 create the connection object
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system",
"nikhil.nik");
/*
* Hostname: Host system for the Oracle database. For your Express
* Edition database, the hostname is localhost. Port: Listener port.
* The default is 1521. SID: Database name. The default for Express
* Edition is xe.
*/
// step3 create the statement object
Statement stmt = con.createStatement();
// step4 execute query
ResultSet rs = stmt.executeQuery("SELECT TEST_NAME FROM TEST1");
// System.out.println(rs);
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3));
// step5 close the connection object
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Stacktrace:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.CharCommonAccessor.getInt(CharCommonAccessor.java:132)
at oracle.jdbc.driver.OracleResultSetImpl.getInt(OracleResultSetImpl.java:521)
at dbPrograms.OracleCon.main(OracleCon.java:31)

You selected column TEST_NAME and extracted its values as int. This operation fails because Oracle cannot convert the values accordingly. Use the ResultSet method suitable for the column type.
Also you select one column and access three columns in the ResultSet so you might want to adjust the select command.

Related

Error in using statement in connecting mysql in my java project

screenshot of the codeI want to use statement in connecting mysql and java database, but the code is giving me errors, I want to know where did I go wrong and how I should do it without getting errore
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/sms","root","");
Statement st= (Statement)conn.createStatement();
String sql= "select * from user_login";
}
catch(Exception e){
}![this is the screenshot of the code](https://i.stack.imgur.com/lo8Yo.png)
I tried using this
Alright, so to do JDBC with MySql you need 4 things
Driver Class
Connection URL
Username
Password
Assuming you have already created the database, with name database_name and table data that has 3 columns as id, first_name & last_name
Connection and showing the data in as follows:
import java.sql.*;
import java.util.*;
class ConnectionToDatabase{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","Pa$$word");
Statement statement = connnection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from data");
while(resultSet.next()){
System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
connection.close();
}
}catch(Exception e) { System.out.println(e); }
}
}
And of course, you can use Spring Boot, where a file named application.properties exists inside java.resources, you can specify the connection as - (Copied from Spring docs)
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=databaseusername
spring.datasource.password=databasepassword

Does MySQL Connector/J driver implement JdbcRowSet interface?

I'm trying to get acquainted with JDBC basics throuhg Oracle's "The Java™ Tutorials" and now I got stuck right here: https://docs.oracle.com/javase/tutorial/jdbc/basics/jdbcrowset.html.
For my examples, I exploit MySQL Server with the latest version of Connector/J (mysql-connector-java-8.0.16.jar). So far, the driver worked as expected. It gets connection to MySQL Server, creates database, tables, populates them with data and fills ordinary ResultSet objects with the retrieved data. However, as soon as I try to create JdbcRowSet object and perform execute(), I get SQL exception reporting: "No suitable driver found..."
So, now I'm in doubts: whether JdbcRowSet (as well as CachedRowSet / JoinRowSet / FilteredRowSet / WebRowSet) is just not implemented by Connector/J driver, or I'm doing something wrong? Or maybe this functionality is no longer supported in JDK 11?
Here is an example:
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.*;
import java.util.Properties;
public class JdbcRowSetTest {
public static void main(String[] args) {
String connectionURL =
"jdbc:mysql://localhost:3306/testdb?serverTimezone=Europe/Moscow";
String userName = "root";
String password = "root";
try {
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
System.out.println("Connect to database...");
Connection conn =
DriverManager.getConnection(connectionURL, connectionProps);
System.out.println("Retrieve and process data using ResultSet...");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COFFEES");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
float price = rs.getFloat("PRICE");
System.out.println(coffeeName + ", " + price);
}
System.out.println("Now, update the data using JdbcRowSet...");
JdbcRowSet jdbcRs = RowSetProvider.newFactory().createJdbcRowSet();
jdbcRs.setUrl(connectionURL);
jdbcRs.setUsername(userName);
jdbcRs.setPassword(password);
jdbcRs.setCommand("select * from COFFEES");
// it's where SQLException is thrown
jdbcRs.execute();
jdbcRs.absolute(2);
jdbcRs.updateFloat("PRICE", 10.99f);
jdbcRs.updateRow();
System.out.println("After updating the 2nd row:");
//... view updated table
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And it's the output:
Connect to database...
Retrieve and process data using ResultSet...
Colombian, 7.99
Espresso, 9.99
Now, update the data using ResultSet...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb?serverTimezone=Europe/Moscow
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:643)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:654)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:556)
at JdbcRowSetTest.main(JdbcRowSetTest.java:37)
Updated (possible solution):
As the commentators mentioned bellow, the problem described here has nothing to do with MySQL implementing rowset or not. For me, it seems to be just a bug of JDK 11.0.1, because as soon as I updated for the newer version of JDK 12.0.1, the problem dissipated, and now JdbcRowSet object is created without any MySQLException.

Derby DB table creation and connection

I am writing a set of Eclipse console-based word games and have integrated an embedded Derby DB driver for storing a users result history.
My question is regarding Derby table initialization.
The Derby Database connection itself has a condition checker:
"jdbc:derby:dbName;create=true" So if the DB exists, it connects, if not it creates.
I am stuck on how to do this with a TBL in the Database. Even with the help from this similar question: how to create table if it doesn't exist using Derby Db
I've included my code below. My code throws a sql exception at the query for the Table 'RPS'. (My dbName is 'RPSdb' and TBL name is 'RPS'.)
This exception is caught by my catch block and passed to a static method in a different class ('DerbyHelper'). This static method is setup right now to always return true for the time being.
My question is how to I code my catch block and corresponding helper class so that I can implement the above mentioned TBL functionality?
Connection conn = null;
ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, PreparedStatements
Statement s;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(protocol + dbName + ";create=true");
conn.setAutoCommit(false);
s = conn.createStatement();
statements.add(s);
rs = s.executeQuery("select * from RPS");
rs.next();
int cG = rs.getInt(1) + corGuess;
int iCG = rs.getInt(2) + inCorGuess;
s.executeUpdate("UPDATE RPS SET corGuesses = " + cG
+ ", inCorGuesses= " + iCG);
conn.commit();
}
catch( SQLException e ) {
if( DerbyHelper.tableAlreadyExists( e ) ) {
// what do I do here??
}
}
Interface java.sql.Connection has method getMetaData() which returns java.sql.DatabaseMetaData and that interface contains method getTables() which will tell you whether your database table exists, or not.

Java using teradata giving exception - Only an ET or null statement is legal after a DDL Statement

As per my requirement, I need to pull records from Teradata db. While trying to pull data, I am getting exception as follows.
com.teradata.jdbc.jdbc_4.util.JDBCException: [Teradata Database] [TeraJDBC 14.10.00.09] [Error 3932] [SQLState 25000] Only an ET or null statement is legal after a DDL Statement.
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:307)
at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:108)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:321)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:202)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:122)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.run(StatementController.java:113)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:380)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:322)
at com.teradata.jdbc.jdbc_4.TDStatement.doNonPrepExecuteQuery(TDStatement.java:310)
at com.teradata.jdbc.jdbc_4.TDStatement.executeQuery(TDStatement.java:1085)
at com.uprr.netcontrol.wkfl_mgmt.eventhandler.eventprocessor.TeradataSelectFromVolatileTable.main(TeradataSelectFromVolatileTable.java:26)
I think I got this exception because of using Volatile table in my query. But I need to use volatile table as part of query to make grouping on a particular column to get comma separated column data. Please, suggest me how to get result set while using volatile table in query. Here, I am enclosing sample java program to reproduce the exception.
package com.sample.package;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"CREATE VOLATILE TABLE VT_TEMP AS (" + "SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created.
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}
I think you may need to wrap your CT statement in an explicit, Teradata-mode transaction to resolve the error you are receiving:
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"BT;" + // Begin Teradata-mode Transaction
"CREATE VOLATILE TABLE VT_TEMP AS (" +
"SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created. +
"ET;" + // End Teradata-mode Transaction
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}

jdbc - sql server not showing any output / error in the console

I am trying to connect to sql server 2005 from my Java application using
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionurl = "jdbc:sqlserver://servername\\SQLEXPRESS;" + "database=master";
Connection con = DriverManager.getConnection(connectionurl);
System.out.println("Connected to SQL Server");
String sql = "select * from employee";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
On executing it, I do not get any output / error at the console. What am I missing?
Maybe there is no records in the table employee.
Or it throws an Exception whose e.getMessage() returns ""(I don't think so,but to avoid it,You can use e.printStackTrace() instead).
actually,the correct answer is...
when you insert the record in sql prompt we have to commit that record by command commit;
sql>commit;
even thought when you insert the record after that you can check by command select *from table;
record is inserted successfully...record is there
but in command prompt when we executing java program records are not displaying....
so commit the record when u inserted..
thankyou

Categories