I managed to compile and run the following code in netbeans but I wanted to compile and run using command line statement:
javac –cp "C:\Program Files\Java\jdk1.8.0_45\db\lib\odbc7.jar" OracleDBConnect.java
then run:
java OracleDBConnect.java
But I get the error
no suitable driver found for jdbc:oracle:thin:#localhost:1521:XE
What am I doing wrong?
import java.util.*;
import java.sql.*;
public class OracleDBConnect {
public OracleDBConnect() {
try {
// Load MS access driver class
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (Exception e)
{
System.out.println( e.getMessage() );
// System.exit(0);
}
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String userid = "HR"; // Username here
String password= "HR"; // Password here
String sql = "SELECT * FROM EMPLOYEES";
try (Connection connection = DriverManager.getConnection( url, userid, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
}
public static void main(String[] args) {
new OracleDBConnect();
}
}
You need to set the classpath when you run the class:
java –cp “C:\Program Files\Java\jdk1.8.0_45\db\lib\odbc7.jar” OracleDBConnect
It is not needed to include odbc7.jar when you compile it since you do not directly reference a class from it.
You need to add dependent libraries in the classpath and execute java, ex: java -cp <libs ; separated> ClassName
Related
Im trying to insert data into SQL SERVER 2008 database through java class. Here is my code:
public class DB_Sample
{
public static void main (String[] args)
{
try
{
String dbUrl = "jdbc:microsoft:sqlserver://ZAFRAN-PC:1433;databaseName=presentasi;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();;
Connection con = DriverManager.getConnection(dbUrl);
Statement st = con.createStatement();
st.executeUpdate("Insert into barang(nama_barang, jumlah_stok, merk, harga_barang) values('HANDUK','30','ADIDAS','25000')");
con.commit();
ResultSet rs = st.executeQuery("select * from barang");
String i1="";
while(rs.next())
{
i1 = rs.getString(1);
System.out.println("Nama barang: " +i1+ " Berhasil Diinputkan");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Also i add sqljdbc4.jar in CLASSPATH.
.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar;
But when i run my java class throug CMD i got an error message like this:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
So whats the problem i have ? and how i can fix this problem ?
I'm trying to connect with MS-Access using java but When I Compile this code it gives me no error and compile fine but it doesn't show any result while the database has records in it, table name and field name are also correct, anyone can please help me that what I'm doing wrong in it.
import java.sql.*;
public class database{
Connection dbCon;
Statement statement;
ResultSet result;
public database(){
connect();
}
public void connect(){
try{
String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(Driver);
String Sdb = "jdbc:odbc:students";
dbCon = DriverManager.getConnection(Sdb);
statement = dbCon.createStatement();
String sqlQuery = "SELECT * FROM StudentInfo";
result = statement.executeQuery(sqlQuery);
while(result.next()) {
//String name = result.getString("Studentname");
System.out.println(result.getString("Studentname"));
}
}catch(Exception ex){
}
}
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
new database();
}
}
You are not getting error during execution of program because you are eating exception here:
catch(Exception ex){
}
You should try to print the exception trace to know what is going wrong.
catch(Exception ex){
ex.printStackTrace();
}
I'm trying to make a custom MySQL class in Java but I'm getting a few exceptions, here's my code:
MySQL.java:
package evo.common;
import java.sql.*;
public class MySQL {
private static String hostname;
private static String username;
private static String password;
private static String database;
public MySQL(String host, String user, String pass, String db)
{
hostname = host;
username = user;
password = pass;
database = db;
}
public static void Error(Exception ex)
{
System.out.println("Fatal Error: "+ex.getMessage());
}
public static void SQLError(SQLException ex)
{
System.out.println("Fatal SQL Error: "+ex.getMessage());
}
private static Connection connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch(Exception e){
Error(e);
}
String url = "jdbc:mysql://"+hostname+":3306/"+database;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch(SQLException ex){
SQLError(ex);
}
return conn;
}
public static ResultSet result(String query)
{
Connection conn = connect();
PreparedStatement pst = null;
ResultSet rs = null;
try
{
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch(SQLException ex){
SQLError(ex);
}
return rs;
}
public static void main(String args[]){}
}
Test.java:
package evo.common;
import java.sql.*;
public class Test {
public static void main(String args[])
{
MySQL mysql = new MySQL("localhost", "root", "******", "souljaz");
ResultSet res = mysql.result("SELECT * FROM users");
}
}
When I run Test I get these error messages in the console:
Fatal Error: com.mysql.jdbc.Driver
Fatal SQL Error: No suitable driver found for jdbc:mysql://localhost:3306/souljaz
Exception in thread "main" java.lang.NullPointerException
at evo.common.MySQL.result(MySQL.java:58)
at evo.common.Test.main(Test.java:8)
I'm quite new to Java so help appreciated. thanks.
Download the lastest version of Connector/J and included it in your Classpath. If you are using an IDE this is only a matter of including the jar in your referenced libraries. If you are doing everything by hand, refer to this official guide:
java -cp "bin;lib/mysql-connector-java-5.1.30-bin" evo.common.Test
Update:
In Eclipse: Right click your project in Package Explorer, then:
Properties -> Java Build Path -> Add JARS... (if lib is in the project)
or Add External JARS... (if it is external)
My code is-
package textmessenger;
import java.sql.*;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
try {
String con = "jdbc:mysql://SQL09.FREEMYSQL.NET:3306/a5189576";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int updateQuery = 0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(con, "user", "pwd");
statement = connection.createStatement();
String QueryString = "select * from names";
rs = statement.executeQuery(QueryString);
System.out.println("Executed");
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I run this program, I get "Error" in the output. Where am I going wrong?
I have tried the SQL editor in NetBeans and it works perfectly fine there.
Thanks in advance :)
From the stacktrace you've now posted, You need to download the MySQL JDBC driver and include it in your project:
http://dev.mysql.com/downloads/connector/j/
I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?