Jdbcrowset bug ? return nullpointer exception! - java

package CrimeFile;
import com.sun.rowset.JdbcRowSetImpl;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.JdbcRowSet;
/**
*
* #author singgum3b
*/
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
JdbcRowSet jrsi=new JdbcRowSetImpl();
jrsi.setUrl("jdbc:sqlserver://localhost:1433;databaseName=CrimeFile");
jrsi.setUsername("sa");
jrsi.setPassword("hellokitty");
jrsi.setCommand("select * from dbo.Target");
jrsi.execute();
}
catch (SQLException ex) {
Logger.getLogger(test.class.getName()).log(Level.ALL, null, ex);
}
}
}
Exception:
Exception in thread "main" java.lang.NullPointerException
at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:666)
at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:553)
at CrimeFile.test.main(test.java:30)
Java Result: 1
(line 30 is crsi.excute();)
I'm using sql server 2008 and ms jdbc 3.0.I googling around and found out this code is the same as in Sun's example link .Am i wrong?

I was having the same problem and came to conclusion that the problem is that Microsoft driver doesnt support combination of conn.prepareStatemen(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); as stated
at microsoft website
resulting in exception of prepare() method.
I took source code from here created my own MyJdbcRowSetImpl and changed parameter of prepareStatement to ResultSet.TYPE_SCROLL_SENSITIVE
Jtds driver wasnt solution as it doesnt support rowsets.

Ok, the answer was to switch to JtDS driver, which can be found here
There's clearly something bollixed up in MS JDBC driver.

I remember this NullPointerException happening to me but only if I call execute() when I should NOT be doing so i.e. when using JdbcRowSetImpl with a ResultSet as argument
private JdbcRowSet executeWithResultSet(Connection conn, String sqlQuery)
throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);
jdbcRs.execute(); //<-- results to the error as reported
return jdbcRs;
}

Related

Cant make connection with MariaDB and Java

Im trying to create web app using java and mariadb but i encountered problem when tried to implement mariadb to login. Here my code:
initSql:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
#WebServlet("/initSql")
public class initSql extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public initSql() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
Connection conn = null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/baza_new", "root","root");
System.out.println("db povezana");
}catch(Exception e){
//JOptionPane.showMessageDialog(null, e);
System.out.println("db NIiiJE povezana");
//return null;
}
}
}
LoginDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.initSql;
public class LoginDAO {
static Connection con = null;
public static boolean validate(String username, String password, String type) {
boolean status = false;
try {
con = initSql.init();
System.out.println("1");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
//pst.setString(1, type);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
status= rs.next();
con.close();
}catch(Exception e) {System.out.print(e);}
return status;
}
}
and i get markers:
Cannot make static reference to non-static method from type generic servler
Type mistmatch cannot connect from void to Connection
I'm little bit stuck with this problem.Can someone help me with my code?
People seem to be neglecting the more broad-scale issues in your code. There are standards to follow like capitalization etc but overall you have some bigger issues.
You shouldn't be making erroneous instances of initSql as it's an HttpServlet, it just doesn't make sense. You also have static/non-static references to a Connection field when you don't need it. To start with, change initSql#init to return a Connection, and while I normally wouldn't recommend abusing static this way, make the method itself static:
//returns a connection, requires no class instance
public static Connection init(ServletConfig config) { ... }
From there, we can now retrieve a Connection instance by calling this method:
Connection con = initSql.init();
Overall you should have a proper class or design for handling this, but for simple learning this is "okay".
Secondly, you're not quite using ResultSet correctly. #next will determine if there is an available row to point to from the SQL results, and if so it moves the marker to the next row. You would use it in order to check if you can retrieve results:
ResultSet set = /* some sql query */;
String someField;
if (set.next()) {
//gets the value of the column "my_field"
someField = set.getString("my_field");
} else {
//no results!
someField = null;
}
Alternatively, if you were looking for multiple results you can loop over #next
while (set.next()) {
//just one value out of many
String myField = set.getString("my_field");
}
In this use-case it's alright to check if the row exists, but I would personally check against something like user permissions or somesuch. If you relied on code like this for something sensitive you might expose something you don't want to.
Overall, I would work a little more on your logical structure for the code, and maybe go over some of the basics for Java and common coding standards for it (Google and Oracle have good guides for this).
Firstly, your class name initSql should have Capitalized first letter to follow conventions.
Secondly, you should either create an instance/object of InitSql and then call the method init() on that object or make the init() method static.
initSql.init() isn't static, which is not a problem of MariaDB and its connection from Java :) To fix this error you can add static to the mentioned method. But: As there are multiple errors in your code (e.g. assigning the result of a void method to a variable), it will not work then either..

Hive server not starting

Iam new to the hadoop ecosystem. Tried to access hive through jdbc. For that I have written the following code
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveConnection {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select * from test.employees");
while (res.next()) {
System.out.println(res.getString(1));
} }}
and started the hiveserver2 (hive version 0.12 & hadoop version 1.1.2) through the terminal and im getting the status as "Starting HiveServer" . When i tried executing the above code from eclipse im no getting any error and any results neither(Got the same when i executed the executable "hiveserver" ).
Can any one help me out.
Thanks in advance.
Following ways are most really reason for your problem.
1.Is the hive-jdbc-*.Jar having classpath like this "org.apache.hadoop.hive.jdbc.HiveDriver" or "org.apache.hive.jdbc.HiveDriver"?
2.While connection,you need to pass the user name and password like this?
If you use hive server2 then you have to set the connection like below.
con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Above ways are really helpful for you.
Thanks in advance.

class not found exception com.mysql.jdbc.driver [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
File structure of my project is:
-src
|
-pkg
|
-CoreServlet.java(servlet)
-Main.java
-Core.java(jdbc code is here)
core.java class:
package com.pkg;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class core{
private Connection connect = null;
private Statement statement =null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
String qwerty;
public void readDataBase() {
String userName = "ansh";
String password = "12345";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/glbitm", userName,password);
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from teachers");
resultSet.next();
qwerty = resultSet.getString(1);
} catch (Exception e) {
System.out.println(e);
}
}
}
coreServlet.java class :
package com.pkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class coreServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
core dao = new core();
dao.readDataBase();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></head>");
pw.println("<div>"+dao.qwerty+"</div>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
When I am accessing dao.qwerty in my coreServlet.java in my tomcat server. I am getting class not found exception com.mysql.jdbc.driver and value of dao.qwerty is printed as null. Where I am doing wrong ?
You need to add the mysql connector in classpath.
http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.4/mysql-connector-java-5.1.4.jar
This connector jar acts as a mediator between database and the application for the flow of data. You can extract the class files from jar and see the details.
The java.lang.ClassNotFoundException is thrown when your code attempts to execute the following line
Class.forName("com.mysql.jdbc.Driver").newInstance();
This is a checked exception which always needs to be either caught inside a try/catch or if try/catch is not implemented, then this exception needs to be declared in the method.
There have been multiple resolutions provided in this thread, but from my experience if you are able to connect to your database from eclipse using data source explorer, then most likely reason is "mysql-connector-java-5.1.28-bin.jar" is not copied into the your tomcat's lib directory.
The mysql connector for java can be downloaded from http://dev.mysql.com/downloads/connector/j/
You have not set the mysql-connector in your path.Set that first and everything else will be done
What is JConnector ?
Java does not know SQL so every statement you want to execute using the sql driver will get converted to sql constructs and the result that is returned my mysql is also converted into java understandable constructs.
hope it helps

JDBC connectivity issue

My code for connection with access database is this...its working fine here... i have tried to connect my database with java derby embedded database but always getting sql exception assuming the same table what changes do i need to connect my application with java derby embedded database??
package database;
import java.sql.*;
import javax.swing.JOptionPane;
public class database {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String url = "jdbc:odbc:personnew";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection(url);
Statement st=con.createStatement();
String sql="SELECT * FROM Person";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
String id=rs.getString("id");
String name=rs.getString("name");
String fathername=rs.getString("fathername");
JOptionPane.showMessageDialog(null,id+"\t"+name+"\t"+fathername);
}
// TODO code application logic here
}catch(Exception sqlEx){
System.out.println("Sql exception");
}
}
}
For one thing, You would need to use the correct JDBC driver; org.apache.derby.jdbc.EmbeddedDriver
http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
The tutorial in general is probably where you want to start as it tells you everything you need to know:
http://db.apache.org/derby/papers/DerbyTut/index.html

Error in My java oracle connectivity ... java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I just got some errors in my Java oracle connectivity. Could anyone please help me with this? I have enclosed the code below. I'm getting this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver..
this is the code
package md5IntegrityCheck;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MD5IntegrityCheck
{
public static void main(String[] args)
{
String fileName,Md5checksum ,sql;
Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 =DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
}
catch(Exception ee)
{ee.printStackTrace( );}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/****insert method******/
private static void setDefaultCloseOperation(String exitOnClose) {
// TODO Auto-generated method stub
}
static void setVisible(boolean b) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
PreparedStatement pst = con.prepareStatement("insert into RecordTbl values(?,?)");
String fileName = null;
pst.setString(1,fileName);
String Md5checksum = null;
pst.setString(2,Md5checksum);
int i=pst.executeUpdate( );
System.out.println("recorded in database");
con.close( );
}
catch(Exception ee)
{ee.printStackTrace( );}
}
}
if (args.length <= 0)
{
Md5Gui gui = new Md5Gui();
gui.runGui();
}
else
{
DoWork runningProgram = new DoWork();
runningProgram.run(args);
}
}
}
Your question is vague:
In your exception, you're getting a ClassNotFoundException for a driver that pertains to MySQL. On your code, you're using a JDBC-ODBC Driver.
My suggestion is how did you configure your database connectivity. Let's start from there. Also, it would be better to add the exception stack trace to see exactly what's happening.
Edit: Visit this example if you want to know how to configure JDBC connection to Oracle Database. I fully recommend using the Oracle JDBC driver directly instead of connecting it to an ODBC Bridge.
I assume you might be running your program in IDE, so please add drivers jars in the classpath of project
You should look into any 3rd party library you're using whether there a MySQL database driver is needed. Although you write you are using an Oracle driver (though the JdbcOdbcDriver is provided by Java itself and has nothing to do with Oracle DB's) the exception is clearly stating that the MySQL is requested. Since you don't use it in the code you provided, there must be another database connection using MySQL.

Categories

Resources