SQL error in database connection - java

I am getting an SQL error while establishing database connection in Java (Jdbc:Odbc). How do I fix this error?
Here is the relevant code:
import java.sql.*;
import java.lang.*;
import java.io.*;
public class db {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:data","system","password");
System.out.println("\n connection established");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from stud");
System.out.println("details of empdata\n");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
} catch(Exception e) {
System.out.println("sql error");
}
}
}

/* Execute query requires string as argument and u have not use semi colon at query if u are getting class not found exception than handle it first
THIS SHOULD BE PASS IN DOUBLE QOUTES="select * from stud;"*/
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:data","system","password");
System.out.println("\n connection established");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from stud;");//----HERE--*/
System.out.println("details of empdata\n");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
} catch(Exception e) {
System.out.println("sql error");
}
}
}

Related

How do i verify whether my code has access to table

I am learning Java getting trouble in JDBC connection.
Following is my code:
public class DemoPro {
public void test() {
Connection con;
Statement stmt;
ResultSet rs;
System.out.println("Looking for connection");
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dburl="jdbc:ucanaccess://E://WEB Project//SCMPayBoard//Database/SCMEmpPayment.accdb";
con=DriverManager.getConnection(dburl,"","");
System.out.println("Connection successfully");
stmt=con.createStatement();
String verify = "Select * from TestTable";
stmt.executeQuery(verify);
rs = stmt.getResultSet();
System.out.println("Executing Query");
while(rs.next())
{
System.out.println("Result/n/n/n");
System.out.println(rs.getString(2) + " : " + rs.getString(3));
}
System.out.println("Closing Connection");
con.close();
}catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DemoPro.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
DemoPro dp=new DemoPro();
dp.test();
}
}
Output :
Looking for connection
Connection successfully
Executing Query
Closing Connection
BUILD SUCCESSFUL (total time: 1 second)
All sysout is executing but Table data is not fetched
How do i know Table is getting access or not
What should i do getting no result as expected

How to connect java to Ms access Database [duplicate]

This question already has an answer here:
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 5 years ago.
i'm trying to connect the java to ms access database but it didn't work really well
and i got an error message like this
sun.jdbc.odbc.JdbcOdbcDriver
this is my code :
import java.sql.*;
public class main{
public static void main(String[] args) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver(*.accdb)};DBQ=D:\\Andries\\testdatabase.accdb");
Statement st = con.createStatement();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
you can use ucanacess.jar for connect Ms Aceess database
show some example here http://www.benchresources.net/jdbc-msaccess-database-connection-steps-in-java-8/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MsAccessDatabaseConnectionInJava8 {
public static void main(String[] args) {
// variables
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
// Step 1: Loading or registering Oracle JDBC driver class
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
}
catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading or "
+ "registering MS Access JDBC driver");
cnfex.printStackTrace();
}
// Step 2: Opening database connection
try {
String msAccDB = "D:/WORKSPACE/TEST_WORKSPACE/Java-JDBC/Player.accdb";
String dbURL = "jdbc:ucanaccess://" + msAccDB;
// Step 2.A: Create and get connection using DriverManager class
connection = DriverManager.getConnection(dbURL);
// Step 2.B: Creating JDBC Statement
statement = connection.createStatement();
// Step 2.C: Executing SQL & retrieve data into ResultSet
resultSet = statement.executeQuery("SELECT * FROM PLAYER");
System.out.println("ID\tName\t\t\tAge\tMatches");
System.out.println("==\t================\t===\t=======");
// processing returned data and printing into console
while(resultSet.next()) {
System.out.println(resultSet.getInt(1) + "\t" +
resultSet.getString(2) + "\t" +
resultSet.getString(3) + "\t" +
resultSet.getString(4));
}
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
finally {
// Step 3: Closing database connection
try {
if(null != connection) {
// cleanup resources, once after processing
resultSet.close();
statement.close();
// and then finally close connection
connection.close();
}
}
catch (SQLException sqlex) {
sqlex.printStackTrace();
}
}
}
}

How to get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

java.sql.SQLException: Invalid handle

I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'

Getting null pointer exception in JDBC(mySql) program

I checked everything like username, password, db_url, table name, etc but still I get this output---connecting to database
creating statement
java.lang.NullPointerException
here is my code, (I'm using eclipse Kepler EE and MySQL 5.6.17.0)
import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
conn=DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("creating statement");
String sql="select * from sample";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int eid=rs.getInt("id");
String ename=rs.getString("name");
System.out.print(eid+"\t");
System.out.print(ename);
System.out.println("");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
}
}catch(Exception e)
{
System.out.println(e);
}
try
{
if(conn!=null)
{
conn.close();
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
I don't think your statement is set. It is always null.
I think you should use this:
stmt = conn.createStatement( );
You didnt create stmt object
stmt = conn.createStatement( );
You have to add above line before this line ResultSet rs=stmt.executeQuery(sql);
You are executing query on a null object.
So getting NPE
You set Statement stmt=null; and you never initialize it later.

Categories