jdbc connection established but didnt print the result in eclipse console - java

I am new to this forum....
Iam tring to connect java project created in eclipse with oracle database xe,
I followed the procedures as descrided in the following link
https://www.youtube.com/watch?v=fMp63HsIRbc
but it didnt print the result in the eclipse console but it also didnt throw the exception as well
what should be the reason
this is my code
package dbmsoracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdb {
public static void main(String[] args) {
System.out.println("jen");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
Statement st = con.createStatement();
String sql="select * from muhil";
ResultSet rs =st.executeQuery(sql);
while (rs.next())
{
System.out.println("executing ...");
System.out.println(rs.getInt(1)+" "+rs.getInt(2));
System.out.println("executed");
con.close();
}
}
catch (Exception e)
{
System.out.println("connection failed");
System.out.println(e);
}
}
i have downloaded my jdbc driver
Oracle Database 11g Release 2 (11.2.0.4) JDBC Drivers
ojdbc6.jar
Certified with JDK 8, JDK 7 and JDK 6: ......
and iam using jdk 8

Firstly check that your connection is establishing with oracle database or not. Here is the connection code try this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}

I have the same problem. The problem is your code doesn't catch(SQLException e). Because just catch(Exception e) will not make the exception of sql shown in the console. After doing this, you will probably find the Exception is "No suitable driver found for jdbc".
Then, either you can download the mysql-connector-java and add it to your lib, or if your project is Maven, you can just add dependency in your pom file.

After you used Sql+ for entering database, commit the table. Enter 'commit'(without quotes) on the terminal or either close your Sql+ terminal. In your case, you must have closed the terminal after you changed your id from 24, 253 to 1, 2. That is why it ran properly. Got nothing to do with id starting from 1

first of all go and check if your table has any data or not. It seems you just created this table 'muhil' before writing the above code. i'm pretty sure You must have entered some data as well in your new table. Just make sure you have Committed your transaction in the MYSQL Workbench. Just commit it and try to run your code in eclipse again.

Related

Unable to get Oracle database connection,oracle.net.ns.NetException: Undefined Error

I wanted to connect to an Oracle database using JDBC.
I installed ojdbc6.jar properly and wrote this code.
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:#192.168.127.129:1521:helowin";
String id = "msa_checkin";
String pass = "msa0526";
Connection con = DriverManager.getConnection(url, id, pass);
if(con != null)
System.out.println("Oracle success");
else
System.out.println("Oracle failed");
}
catch(Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
But the output looks like this.
Error
java.sql.SQLException: Undefined Error
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:531)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:221)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.kinth.DBConnect.main(DBConnect.java:14)
Caused by: oracle.net.ns.NetException: Undefined Error
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:385)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
... 7 more
I search for similar questions,but it doesn't solve my problem.
Unable to get Oracle database connection, should I format my computer?
No problem with Navicat.
Navicat Image
I tried using oracle6.jar and Oracle14.jar but neither worked.
Can you follow the instructions on this page and try to get a connection using the latest JDBC drivers?

Connecting to SQL Express DB: connection refused

I have SQL Express 2012 installed on my local machine. I tried connecing with it, by using JDBC 6.2. I downloaded it and declared the dependency(IntelliJ: CTRL, SHIFT, ALT + S --> "Modules" --> "Add" --> "Jars or directories").
Eventually I adjusted the provided code above to my needs, looking like the following:
For some reason, the imported class is not being used at all(it´s greyed out by IntelliJ) - did I made a mistake in terms of dependencies? I´m fairly new to JAVA: to my understanding, setting up the classpath is equal to setting up the depndencies(?).
Moreover I get the error "connection refused". I checked different login credentials as well as the ports(SQL configuration manager as well as netstate) - they are fine. Both, Windows- and SQL authentication didn´t work.
What am I missing?
package com.company;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class Main {
public static void main(String[] args) {
String connectionString = "jdbc:sqlserver://localhost:1433;"
+"database=QMT;"
+"user=superadmin;"
+"password=myPassword.;";
// Declare the JDBC objects.
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}

How to use XAMPP MySQL database with my Java Application?

I have used in the past few months XAMPP with MySQL database(s), which were created and modified with phpMyAdmin on localhost, for my university JavaEE projects. The MySQL database and Apache server are started from the XAMPP Control Panel. Everything went fine.
Now I am developing my own Java Desktop Application using JavaFX/Scene Builder/FXML and I want to use a database to store and load various information processed by the Java Application through JDBC.
The question is, how to start the MySQL database on localhost, without using the XAMPP Control Panel manually, when I finish my Java Application and deploy it as stand alone program and start it just from a single shortcut?
Any way to make the shortcut of the program also start the MySQL database on my PC before/while it starts the Java Application? Or maybe there is a way to do that inside the Java code? Or maybe some other way, that is not known to me?
I am not strictly determined on using only the XAMPP/MySQL/phpMyAdmin setup, it is just already all installed on my PC and I know how to work with it, thus the easiest solution so far. So if there is some better way/database setup for home/small applications, please feel free to suggest some :). I am not sure at all if what I want to do is possible with the XAMPP setup.
Side note: I persist on using localhost DB instead of Serialisation/Deserialisation with Java, because I want the Application to be independent of internet connection and yet have the opportunity to have a ready DB to be transferred to an online DB, if such I decide to do it in the future.
On the root of the Xampp folder you have one mysql_start.bat and one mysql_stop.bat, for start/stop the mysql database included on the Xampp package.
You can use they in another bat you should create to start your Java Desktop application.
ProcessBuilder P1 =new ProcessBuilder("C:\\xampp\\mysql_start.bat");
P1.start();
ProcessBuilder P2 =new ProcessBuilder("C:\\xampp\\APACHE_start.bat");
P2.start();
You can do it like this -
To connect to the Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Statement statement;
//function to connect to the xampp server
public void DatabaseConnect(){
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/javafx","root","");
/*here javafx is the name of the database and root is the username of
your xampp server and the field which is blank is for password.
Because I haven't set the password. I have left it blank*/
statement = conn.createStatement();
System.out.print("Database Connected");
} catch (Exception e) {
System.out.print("Database Not Connected");
}
}
Below given are the various operations you can perform after connecting to the database.
//for inserting data
public void insert(){
try{
String insertquery = "INSERT INTO `tablename`(`field1`, `field2`) VALUES ('value1', 'value2'";
statement.executeUpdate(insertquery);
System.out.print("Inserted");
} catch(Exception e){
System.out.print("Not Inserted");
}
}
//for viewing data
public void view(){
try {
String insertquery = "select * from `table_name` where field = 'value1'";
ResultSet result = statement.executeQuery(insertquery);
if(result.next()){
System.out.println("Value " + result.getString(2));
System.out.println("Value " + result.getString(3));
}
} catch (SQLException ex) {
System.out.println("Problem To Show Data");
}
}
//to update data
public void update(){
try {
String insertquery = "UPDATE `table_name` set `field`='value',`field2`='value2' WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Updated")
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
//to delete data
public void delete(){
try {
String insertquery = "DELETE FROM `table_name` WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Deleted");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
Also, don't forget to add the JAR file in your system library. For this example, I have used mysql-connector-java-5.1.46

Creating a java program which getting SQLite data and Insert in Oracle DB

I've just started my adventure with programming in SQL using JAVA.
I have Linux and Oracle Database on VirtualBox Machine.
My project is about situation, when a client give me a SQLite3 Database and I have to convert it to Oracle Database.
I've read some code but it gives error
Code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "Move" AS
import java.sql.*;
import java.io.*;
public class getting {
public static void doIt() throws Exception{
Connection conn;
ResultSet rs;
Statement stat;
try{
Class.forName("org.sqlite.JDBC");
conn =
DriverManager.getConnection("jdbc:sqlite://127.0.0.1/media/sf_SHARE/baza.db");
} catch (SQLException e){
throw new RuntimeException(e);
}
try{
stat = conn.createStatement();
try{
rs = stat.executeQuery("SELECT * from entities");
while(rs.next()){
String w1= rs.getString("ID");
String w2 = rs.getString("TEXT");
System.out.println(w1+w2);
}
}finally{}
}finally{}
{try {rs.close();
}catch (Exception ignore){}
try {conn.close();
}catch (Exception ignore){}
try {stat.close();
}catch (Exception ignore){}
}
}
}
/
create or replace function Move return varchar2 as
language java name 'getting.doIt() return java.language.String';
/
select Move from dual;
I've got a error:
java.lang.ClassNotFoundException: org/sqlite/JDBC
Is connection in DriverManager.getConnection() is good?
Any ideas what I did wrong?
Cheers
najdzion
You have to download JDBC driver from here: https://bitbucket.org/xerial/sqlite-jdbc/downloads and import downloaded JAR to your project.
Also, as good practice, don't store connections as hard-coded strings.
If you are using maven, check your dependencies:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.8.11.2</version>
</dependency>
Add your jar co Classpath:
> javac Example.java
> java -classpath ".;sqlite-jdbc-(VERSION).jar" Example # in Windows
or
> java -classpath ".:sqlite-jdbc-(VERSION).jar" Example # in Mac or Linux
or you can do it via your IDE.

What is the purpose of calling Class.forName() without saving a reference to the object it returns?

In the example below showing how to use Java's SQL library, Class.forName() is called without a variable to save a reference to the object. What is the purpose of doing this if you cannot manipulate it later? I've seen that line written in various examples of the SQL library.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
It makes the class initializer run - which in the case of JDBC drivers used to be the way that the driver would register itself with DriverManager. In modern Java, JDBC drivers are usually found using the service provider API.
From the docs:
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

Categories