Using SQL Database in Java [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I want to access a table I created and print it within the console of Eclipse. However, I keep getting an error message that says this:
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.createStatement()" because "databaseSQL.conAdministrator" is null.
I also uploaded a jar file: mysql-connector-java-8.0.26.jar
However, my openDataBaseConnection method returns that the database is connected.
My code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.sql.DriverManager;
public class databaseSQL {
private static Connection conAdministrator;
public static void main(String[] args) {
openDataBaseConnection();
LoadListFromDatabase();
}
public static void LoadListFromDatabase() {
String strConnect = "jdbc:mysql://localhost:3306/DBexample";
String sql = "SELECT * FROM employeeInfo";
Statement sqlCommand = null;
ResultSet rstTSource = null;
openDataBaseConnection();
try {
sqlCommand = conAdministrator.createStatement();
rstTSource = sqlCommand.executeQuery(sql);
while(rstTSource.next()) {
String name = rstTSource.getString(1);
System.out.println(name);
}
} catch(Exception e) {
System.out.println(e);
}
}
public static boolean openDataBaseConnection() {
Connection conAdministrator = null;
String strConnect = "";
boolean blnResult = false;
try {
strConnect = "jdbc:mysql://localhost:3306/DBexample";
conAdministrator = (Connection)DriverManager.getConnection(strConnect, "root", "Classof2017!");
if(conAdministrator != null) {
System.out.println("Database is Connected!");
blnResult = true;
}
} catch(Exception e) {
System.out.println("Not Connected!");
}
return blnResult;
}
public static boolean closeDataBaseConnection() {
boolean blnResult = false;
try {
if(conAdministrator != null) {
if(conAdministrator.isClosed() == false) {
conAdministrator.close();
conAdministrator = null;
}
}
blnResult = true;
System.out.println("Database is Closed.");
} catch(Exception e) {
System.out.println(e);
}
return blnResult;
}
}
This is the SQL table I am trying to display in the console:
USE DBexample;
CREATE TABLE employeeInfo(intEmployeeID INT,
strFirstName VARCHAR(20),
strLastName VARCHAR(20),
strHomePhone VARCHAR(20),
strEmail VARCHAR(30),
dtmDateOfBirth DATE);
INSERT INTO employeeInfo VALUE('123000','Brittney', 'Pugh', '(513)738-4730', 'pughb#email.com', '1998-12-01');
INSERT INTO employeeInfo VALUE('246000', 'Emilee', 'Peters', '(513)222-9876', 'emileep#email.com', '1990-05-21');
INSERT INTO employeeInfo VALUE('689000', 'Sally', 'Jenkins', '(513)456-2590', 'jenkinssally#email.com', '1985-03-23');
INSERT INTO employeeInfo VALUE('537000', 'John', 'Smith', '(513)889-0754', 'SmithJ#email.com','1995-07-07');
SELECT * FROM employeeInfo;

pay attention on your openDataBaseConnection() method. You are declaring again the conAdministrator variable e so the openDataBaseConnection is using conAdministrator as method variable and not the class variable.
Try this version of openDataBaseConnection:
/**
* Name: openDataBaseConnection
* ABSTRACT: Opens the connection to the database
* #return blnResult determining factor if the database is connected
*/
public static boolean openDataBaseConnection() {
// Connection conAdministrator = null;
String strConnect = "";
boolean blnResult = false;
try {
strConnect = "jdbc:mysql://localhost:3306/DBexample";
conAdministrator = (Connection)DriverManager.getConnection(strConnect, "root", "Classof2017!");
if(conAdministrator != null) {
System.out.println("Database is Connected!");
blnResult = true;
}
}
catch(Exception e) {
System.out.println("Not Connected!");
}
return blnResult;
}
I hope can help you

Its because you have the variable conAdministrator twice. Once in the Attribute-Section of the class and once at the top of the method openDataBaseConnection, so the connection gets written into the variable in the function.
Removing the first line of the method should solve that problem.
To avoid such bugs in the future, try to access variables which are not in the method with the keyword this

Related

MYSQL JDBC java.sql.SQLException: Operation not allowed after ResultSet closed

I have a program that queries a database using different jdbc drivers. This error is specific to the MySQL driver.
Here's the basic rundown.
I have another query runner class that uses a postgresql jdbc driver that works just fine. Note the line conn.close(); this works fine on my postgresql query runner, but for this SQL runner it comes up with the error.
I have removed the line conn.close(); and this code works fine, but over time it accumulates sleeping connections in the database. How can I fix this?
New Relic is a third party application that I am feeding data to, if you dont know what it is, don't worry it's not very relevant to this error.
MAIN CLASS
public class JavaPlugin {
public static void main(String[] args) {
try {
Runner runner = new Runner();
runner.add(new MonitorAgentFactory());
runner.setupAndRun(); // never returns
}
catch (ConfigurationException e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
}
}
MYSQL QUERY RUNNER CLASS
import com.newrelic.metrics.publish.util.Logger;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryRunner {
private static final Logger logger = Logger.getLogger(MySQLQueryRunner.class);
private String connectionStr;
private String username;
private String password;
public MySQLQueryRunner(String host, long port, String database, String username, String password) {
this.connectionStr = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false";
this.username = username;
this.password = password;
}
private void logError(String message) {
logger.error(new Object[]{message});
}
private void logDebugger(String message) {
logger.debug(new Object[]{message});
}
private Connection establishConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logError("MySQL Driver could not be found");
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionStr, username, password);
logDebugger("Connection established: " + connectionStr + " using " + username);
} catch (SQLException e) {
logError("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public ResultSet run(String query) {
Connection conn = establishConnection();
if (conn == null) {
logError("Connection could not be established");
return null;
}
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
conn.close();
return rs;
} catch (SQLException e) {
logError("Failed to collect data from database");
e.printStackTrace();
return null;
}
}
}
AGENT CLASS
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import com.newrelic.metrics.publish.Agent;
public class LocalAgent extends Agent {
private MySQLQueryRunner queryRunner;
private String name;
private Map<String, Object> thresholds;
private int intervalDuration;
private int intervalCount;
public LocalAgent(String name, String host, long port, String database, String username, String password, Map<String, Object> thresholds, int intervalDuration) {
super("com.mbt.local", "1.0.0");
this.name = name;
this.queryRunner = new MySQLQueryRunner(host, port, database, username, password);
// this.eventPusher = new NewRelicEvent();
this.thresholds = thresholds;
this.intervalDuration = intervalDuration;
this.intervalCount = 0;
}
/**
* Description of query
*/
private void eventTestOne() {
String query = "select count(1) as jerky from information_schema.tables;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestOne");
event.add("jerky", rs.getInt("jerky"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* blah
*/
private void eventTestTwo() {
String query = "SELECT maxlen FROM information_schema.CHARACTER_SETS;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestTwo");
event.add("beef", rs.getString("maxlen"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void pollCycle() {
if (this.intervalCount % this.intervalDuration == 0) {
eventTestOne();
eventTestTwo();
this.intervalCount = 0;
}
// Always incrementing intervalCount, keeping track of poll cycles that have passed
this.intervalCount++;
}
#Override
public String getAgentName() {
return this.name;
}
}
The problem is that you are trying to access the ResultSet after the connection is closed.
You should open and close the connection in the method that is calling run() this way the connection will be open when you access and loop through the Resultset and close it in the finally block of the calling method.
Even better would be if you can just loop through the ResultSet in the run() method and add the data to an object and return the object, this way you can close it in the finally block of the run() method.

How to fix the result consisted of more than one row error

I wrote stored procedure in MySQL which looks like this (it works):
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30),
OUT pName VARCHAR(150),
OUT pType VARCHAR(200),
OUT pRetailPrice FLOAT)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE pBrand;
END//
DELIMITER ;
I try to return multiple results and display them. I've tried many ways described here on Stack and in Internet but that does not help me. I have edited my entire code and created a simple one so you can guys paste it and compile. It should work but with error. Here is the code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD)) {
System.out.println("Connected to MySQL database");
CallableStatement cs = conn.prepareCall("{CALL getBrandRows("
+ "?, ?, ?, ?)}");
cs.setString(1, "Brand#13");
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.FLOAT);
boolean results = cs.execute();
while (results) {
ResultSet rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs
.getFloat("p_retailprice"));
}
rs.close();
results = cs.getMoreResults();
}
cs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
ResultSet can handle multiple records.I found some errors in your code.Try these steps
Move your all close method to finally block.
try {
//do something
} catch (Exception e) {
//do something
} finally {
try{
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
//do something
}
}
You can put your result into List. See sample
List<YourObject> list = new ArrayList<YourObject>();
while (rs.next()) {
YourObject obj = new Your Object();
obj.setName(rs.getString("p_name"));
obj.setType(rs.getString("p_type"));
obj.setRetailPrice(rs.getFloat("p_retailprice"));
list.add(obj);
}
Make sure your query is correct and database connection is Ok.
Don't use IN or OUT parameter if you just simply want to display result. And also you should add '%%' in your LIKE clause with the help of CONCAT function. Please try this one:
DELIMITER //
CREATE PROCEDURE getBrandRows(
pBrand VARCHAR(30)
)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE CONCAT("%", pBrand, "%");
END//
DELIMITER ;
I am posting correct solution to everybody who have smiliar problem:
1. Corrected Stored Procedure:
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30))
BEGIN
SELECT p_name, p_type, p_retailprice
FROM part
WHERE p_brand = pBrand;
END//
DELIMITER ;
2. Corrected Java code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
System.out.println("Connected to MySQL database");
cs = conn.prepareCall("{CALL getBrandRows(?)}");
cs.setString(1, "Brand#13");
boolean results = cs.execute();
while (results) {
rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs.getFloat(
"p_retailprice"));
}
results = cs.getMoreResults();
}
} catch (SQLException | ClassNotFoundException e) {
} finally {
try {
if (rs != null ) rs.close();
if (cs != null) cs.close();
if (conn != null) conn.close();
} catch (SQLException e) {
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
Your stored procedure returns more than one row. Just correct logic behind your select query inside the stored procedure it should return only one row.
here how to return multiple value

Failed to Start Derby Database

So I'm quite new to Java and Derby. I'm using both with my Flex app on Tomcat 7.
When I make a call to Java from Flex the login function works fine but my getUserByUsername function does not.
public Boolean loginUser(String username, String password) throws Exception
{
Connection c = null;
String hashedPassword = new String();
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT password FROM users WHERE username=?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
hashedPassword = rs.getString("password");
}
else
{
return false;
}
if(Password.check(password, hashedPassword))
{
return true;
}
else
{
return false;
}
}
catch (SQLException e)
{
e.printStackTrace();throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
}
public User getUserByUsername(String username) throws DAOException
{
//System.out.println("Executing DAO.getUserByName:" + username);
User user = new User();
Connection c = null;
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT * FROM users WHERE username = ?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTeam(rs.getString("team"));
user.setScore(rs.getInt("score"));
}
}
catch (SQLException e)
{
e.printStackTrace();
throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
return user;
}
The stack I get in Flex is useless as far as I can tell:
Flex Message (flex.messaging.messages.ErrorMessage) clientId = 8EB6D37B-7E0B-01B0->AA55-457722B9036C correlationId = A39E574F-CFC6-51FE-6CBE-451AF329E2F8 destination >= service messageId = 8EB6DF4C-650B-BDD7-7802-B813A61C8DC8 timestamp = >1401318734645 timeToLive = 0 body = null code = Server.Processing message = >services.DAOException : java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details. details = null rootCause = ASObject(23393258)>>{message=java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details., suppressed=[], localizedMessage=java.sql.SQLException: Failed to >start database '/Applications/blazeds/tomcat/webapps/testdrive/WEB->INF/database/game_db', see the next exception for details., cause=java.sql.SQLException} >body = null extendedData = null
My first thought was that it was just an error in my function (maybe someone else will notice it) but I've been looking through it for a couple hours and I can't see anything.
After that I thought maybe Derby had a problem with concurrent connections. I saw somewhere that Embedded JDBC can only handle one connection so I changed the driver from Embedded to Client which once again resulted in the login function working and the other an error saying the url in the connection was null. Any thoughts? Thanks ahead of time for any ideas.
EDIT:
package services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.net.URLDecoder;
public class ConnectionHelper
{
private String url;
private static ConnectionHelper instance;
public String getUrl()
{
return url;
}
private ConnectionHelper()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String str = URLDecoder.decode(getClass().getClassLoader().getResource("services").toString(),"UTF-8");
str= str.substring(0, str.indexOf("classes/services"));
if ( str.startsWith("file:/C:",0)){
str=str.substring(6);
}
else{
str=str.substring(5);
}
url = "jdbc:derby:" + str + "database/game_db";
System.out.println("Database url "+url);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static ConnectionHelper getInstance()
{
if (instance == null)
instance = new ConnectionHelper();
return instance;
}
public static Connection getConnection() throws java.sql.SQLException
{
return DriverManager.getConnection(getInstance().getUrl());
}
public static void closeConnection(Connection c)
{
try
{
if (c != null)
{
c.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
There is NO problem with multiple connections in embedded mode. Full stop.
That said, what you may have come across, is that only one jvm process can access the Derby database files at a time. But that jvm may well have 1000s of threads each with their own connection to Derby (resources permitting, of course).

DriverManager no suitable driver mysql

We're having some trouble finding out why we are getting an error message when creating a connection with DriverManager.
Here is our code
package Databank;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
public class Connectie_Databank
{
//Eigenschappen databank
private String connectieString = "";
private Connection connectie = null;
private PreparedStatement prepStatement = null;
private Statement statement = null;
private ResultSet inhoudQuery = null;
//Inloggegevens PhpMyAdmin
private String gebruikersnaam, wachtwoord;
//Constructor met standaardinstellingen
public Connectie_Databank()
{
this.connectieString = "jdbc:mysql://localhost/groep2_festivals";
this.gebruikersnaam = "root";
this.wachtwoord = "";
}
//Constructor met nieuwe data
public Connectie_Databank(String connectionString, String gebruikersnaam, String wachtwoord)
{
this.connectieString = connectionString;
this.gebruikersnaam = gebruikersnaam;
this.wachtwoord = wachtwoord;
}
/**
* Deze methode zorgt ervoor dat er verbinding gemaakt wordt me de databank
*/
public void maakConnectie()
{
try
{
connectie = DriverManager.getConnection(connectieString, gebruikersnaam, wachtwoord);
}
catch(Exception e)
{
System.err.println("FOUTMELDING: " + e.getMessage());
}
}
public void voerQueryUit(String query, List<String> parameters)
{
try
{
if(parameters.size() > 0)
{
//Reden preparedStatement: geen SQL-Injectie!
prepStatement = connectie.prepareStatement(query);
//Lijst met parameters uitlezen om de preparedStatement op te vullen
for(int i=1; i<=parameters.size(); i++)
{
prepStatement.setString(i, parameters.get(i-1));
}
inhoudQuery = prepStatement.executeQuery();
}
else
{
statement = connectie.createStatement();
inhoudQuery = statement.executeQuery(query);
}
}
catch(Exception e)
{}
}
public ResultSet haalResultSetOp()
{
return inhoudQuery;
}
public void sluitConnectie()
{
//ConnectieString leegmaken en alle objecten die te maken hebben met de connectie sluiten
try
{
connectieString = "";
if(connectie != null)
{
connectie.close();
}
if(prepStatement != null)
{
prepStatement.close();
}
if(inhoudQuery != null)
{
inhoudQuery.close();
}
}
catch(Exception e)
{}
}
}
We call our connection class from within a JSP page like this:
<%
Connectie_Databank connectie;
ResultSet res;
connectie = new Connectie_Databank();
connectie.maakConnectie ();
List<String> lijstParams = new ArrayList<String>();
connectie.voerQueryUit ("SELECT * FROM festivals", lijstParams);
res = connectie.haalResultSetOp();
%>
This happens in the head of our page. The first time the page loads, we get an error "no suitable driver found for jdbc mysql" but when we refresh, the information we query is shown correctly.
So, we only get the one error message on first load, after that, no errors occur and everything works normally.
Can anyone help us?
First you need to load JDBC driver before connection
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
//Load Driver
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
con=DriverManager.getConnection(connectieString);
System.out.println ("Database connection established");
make sure you have mysql-connector-java-5.x.x-bin.jar on the classpath when you run your application.

Not Able to give previleges...Openoffice error

This is the code i had written to save the data into the openoffice database.
but its giving error.i m not understanding y it is appearing.
package coop.data;
import java.sql.*;
/**
*
* #author spk
*/
public class Connectionsetting {
private static Connection con;
private static Statement sm;
private static ResultSet rs;
public static void close()
{
try
{
sm.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void connection() {
String db_file_name_prefix = "/home/spk/Desktop/CooperHr/mydb.odb";
/*
If required change the file name if you are working in windows os
connection is in work
*/
try {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Found");
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
System.out.println("Connection Eshtablished");
// con.setAutoCommit(false);
sm=con.createStatement();
// sm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int executeupdate(String query) {
//Execute & update block insert, update, delete statements
int bool = 0;
try {
bool=sm.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
public ResultSet executeQuery(String query) {
//Block Returns single resultset,,,sql statements such as sql select
ResultSet rs=null;
try {
rs = sm.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
public boolean checkTableStatus(String tblName) {
String sql = "selec * from cat";
ResultSet rs=null;
boolean status = false;
int i = 0;
String allTableNames[] = new String[20];
try {
connection();
rs = sm.executeQuery(sql);
while (rs.next()) {
allTableNames[i] = rs.getString(0);
i++;
if (allTableNames[i].equals(tblName)) {
status = true;
break;
} else {
status = false;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
public static void main(String []args)
{
String query,s1,s2,s3,s4,s5,s6,s7,s8;
Connectionsetting cn=new Connectionsetting();
cn.connection();
s1="same";
s2="sam";
s3="923847";
s4="sam";
s5="sam";
s6="sam";
s7="sam";
s8="R01";
query="insert into Agency_Master values("+s1+","+s2+","+s3+","+s4+","+s5+","+s6+","+s7+","+s8+")";
cn.executeupdate(query);
}
}
This is the error..I m getting it when i trying to save the data into the database
Can any one plz tell me where i m wrong.
Thank you.
run:
Driver Found
Connection Eshtablished
java.sql.SQLException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.jdbc.Util.sqlException(Util.java:200)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1805)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(JDBCStatement.java:205)
at coop.data.Connectionsetting.executeupdate(Connectionsetting.java:52)
at coop.data.Connectionsetting.main(Connectionsetting.java:116)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.Error.error(Error.java:76)
at org.hsqldb.SchemaManager.getTable(SchemaManager.java:510)
at org.hsqldb.ParserDQL.readTableName(ParserDQL.java:4367)
at org.hsqldb.ParserDML.compileInsertStatement(ParserDML.java:64)
at org.hsqldb.ParserCommand.compilePart(ParserCommand.java:132)
at org.hsqldb.ParserCommand.compileStatements(ParserCommand.java:83)
at org.hsqldb.Session.executeDirectStatement(Session.java:1037)
at org.hsqldb.Session.execute(Session.java:865)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1797)
... 3 more
BUILD SUCCESSFUL (total time: 0 seconds)
Your connection URL looks iffy... try changing:
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
to
con=DriverManager.getConnection("jdbc:hsqldb:file:"+db_file_name_prefix+";ifexists=true","sa", "");
(adding a colon after "file", and appending the ifexists=true flag, as indicated by: http://hsqldb.org/doc/guide/ch04.html
It looks to me like the AGENCY_MASTER table doesn't exist. You're trying to execute an update statement, and it looks like HSQLDB can't find the AGENCY_MASTER table.
You can check whether the table exists with HSQLDB's built-in client/viewer:
java -cp hsqldb.jar org.hsqldb.util.DatabaseManagerSwing

Categories