The Values are not being dumped into the table temperature_demo - java

I have written this code to remove the duplicate entries from the table and then to insert it into the other table.
The code executes but the values are not being updated into the table.
Query4 is not getting executed.
Any suggestions would be helpful.
Thank you.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class duplicate
{
public static void main(String args[])
{
Statement stat=null,stat1=null,stat2=null;
Connection con=null;
ResultSet result1,result2;
int s_id=0;
String date=null,time=null,temp=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Loaded Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/preprocessor","root","bigdata");
System.out.println("Connected to mysql");
stat=con.createStatement();
stat1=con.createStatement();
stat2=con.createStatement();
String query1="insert into temperature_demo(ddslno,ddtstation_id,ddtdate,ddttime,ddtemp,ddtype_code,ddelevation) select dslno,dtstation_id,dtdate,dttime,dtemp,dtype_code,delevation from temperature_dup where dslno=1";
String query2="select * from temperature_demo";
String query3="select * from temperature_dup";
stat1.execute(query1);
result1=stat1.executeQuery(query2);
result2=stat2.executeQuery(query3);
while(result1.next())
{
s_id=result1.getInt(2);
date=result1.getString(3);
time=result1.getString(4);
temp=result1.getString(5);
break;
}
while(result2.next())
{
int sno=result2.getInt(1);
int s1_id=result2.getInt(2);
String date1=result2.getString(3);
String time1=result2.getString(4);
String temp1=result2.getString(5);
String type_cd=result2.getString(6);
String elev=result2.getString(7);
String query4="insert into temperature_demo values(sno,s1_id,'date1','time1','temp1','type_cd','elev')";
try
{
if( (s_id==s1_id)&&(date.equals(date1))&&(time.equals(time1))&&(temp.equals(temp1)) )
;
else
{
System.out.println(sno+" "+s1_id+" "+date1);
stat1.execute(query4);
}
}
catch(Exception ex)
{
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(con!=null)
try
{
con.close();
}
catch(Exception ex)
{
}
if(stat1!=null)
try
{
stat1.close();
}
catch(Exception ex)
{
}
if(stat2!=null)
try
{
stat2.close();
}
catch(Exception ex)
{
}
}
}
}

I made the changes and the following code is the result.
PreparedStatement pstat;
pstat=con.prepareStatement("INSERT INTO temperature_demo VALUES(?,?,?,?,?,?,?)");
while(result2.next())
{
int sno=result2.getInt(1);
int s1_id=result2.getInt(2);
String date1=result2.getString(3);
String time1=result2.getString(4);
String temp1=result2.getString(5);
String type_cd=result2.getString(6);
String elev=result2.getString(7);
try
{
if( (s_id==s1_id)&&(date.equals(date1))&&(time.equals(time1))&&(temp.equals(temp1)) )
;
else
{
System.out.println(sno+" "+s1_id+" "+date1);
pstat.setInt(1,sno);
pstat.setInt(2,s1_id);
pstat.setString(3,date1);
pstat.setString(4,time1);
pstat.setString(5,temp1);
pstat.setString(6,type_cd);
pstat.setString(7,elev);
}
The first statement in the else block seems to execute perfectly. The following pstat statements(pstat is a preparedStatement variable) aren't executing

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.

Display details on specific user using rest web service, queryparam

I am making a log in form on java. Restful web service. I have done logging in and in registration. I have here inputting plate number. I want to retrieve data based on the inputted plate number. I have here the scanning only of the plate number if it is in the database, but I dont know how to display the details of it. Here's my code. I'm so confused. I don't know how to do it.
Constants.java
package com.taxisafe.connection;
public class Constants {
public static String dbClass = "com.mysql.jdbc.Driver";
private static String dbName= "taxisafe";
public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;
public static String dbUsername = "root";
public static String dbPassword = "";
}
DatabaseConnection.java
package com.taxisafe.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.taxisafe.objects.Objects;
public class DatabaseConnection {
#SuppressWarnings("finally")
public static Connection createConnection() throws Exception {
Connection koneksyon = null;
try {
Class.forName(Constants.dbClass);
koneksyon = DriverManager.getConnection(Constants.dbUrl, Constants.dbUsername, Constants.dbPassword);
} catch (Exception e) {
throw e;
} finally {
return koneksyon;
}
}
//CHECK FOR LOGIN
public static boolean checkUser(String username, String password) throws Exception { //checkLogin to checkUser
boolean UserRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM user WHERE username = '" + username + "' AND password=" + "'" + password + "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
UserRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return UserRecorded;
}
// REGISTER USER
public static boolean registertheUser(String name, String username, String email, String password) throws SQLException, Exception { //inserUser - registertheUser
boolean insertUser = false; //insertStatus - insertUser
Connection konek = null;
try{
try{
konek = DatabaseConnection.createConnection();
}
catch (Exception e){
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "INSERT into user(name, username, emailaddress, password) values('"+name+ "',"+"'" + username + "','"+ email + "','" + password + "')";
int dbrecord = statement.executeUpdate(code);
if (dbrecord > 0){
insertUser = true;
}
} catch (SQLException sqle){
throw sqle;
} catch (Exception e){
if (konek !=null){
konek.close();
}
throw e;
} finally{
if (konek !=null){
konek.close();
}
} return insertUser;
}
//CHECK PLATE NUMBER
public static boolean checkPlate(String platenumber) throws Exception { //checkLogin to checkUser
boolean PlateRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM taxi WHERE taxi_plate_no = '" + platenumber+ "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
PlateRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return PlateRecorded;
}
}
JsonConstruction.java
package com.taxisafe.json;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class JsonConstruction {
public static boolean isNotNull(String text){
return text !=null && text.trim().length() >=0 ? true : false;
}
public static String JSONResponse(String tag, boolean status){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
} catch (JSONException e){
} return object.toString();
}
public static String JSONResponse(String tag, boolean status, String errorMessage){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
object.put("errorMessage", errorMessage);
} catch (JSONException e){
} return object.toString();
}
}
PlateNumberCheck.java
package com.taxisafe.server;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.sun.corba.se.impl.util.Utility;
import com.taxisafe.connection.DatabaseConnection;
import com.taxisafe.json.JsonConstruction;
#Path("platecheck") //for the url
public class PlateNumberCheck {
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/magcheck")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String magcheck(#QueryParam("platenumber") String platenumber){
String sagot = "";
if(checkInput(platenumber)){
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String platenumber){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(platenumber)){
try{
output = DatabaseConnection.checkPlate(platenumber);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
}
Please help me on how to display the details of the plate number.

servlet mysql Runtime Exception [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 7 years ago.
java.sql.SQLException: Parameter index out of range (1 > number of parameters,
which is 0)
For the following code, what kind of parameter change is required to make the code run?
package com.chen.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class SqlHelper {
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
private static String url = "jdbc:mysql://localhost:3306/userdata";
private static String username1 = "root";
private static String password1 = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static Connection getConnection() {
try {
conn = DriverManager.getConnection(url, username1, password1);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void executeUpdate(String sql, String[] parameters) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
ps.setString(i+1 , parameters[i]);
}
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
close(rs,ps,conn);
}
}
public static ResultSet executeQuery(String sql,String[]parameters){
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
if(parameters!=null&&!parameters.equals("")){
for(int i=0;i<parameters.length;i++){
ps.setString(i+1,parameters[i]);
}
}
rs=ps.executeQuery();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
//close(rs,ps,conn);
}
return rs;
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static Connection getConn() {
return conn;
}
public static PreparedStatement getPs() {
return ps;
}
public static ResultSet getRs() {
return rs;
}
}
Below is the error stack:
//java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:904)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3797)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3779)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4600)
at com.chen.util.SqlHelper.executeQuery(SqlHelper.java:100)
at com.chen.services.UserService.checkUser(UserService.java:22)
at com.chen.controller.ControllerServlet.doGet(ControllerServlet.java:33)
at
package com.chen.services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.chen.domain.User;
import com.chen.util.SqlHelper;
public class UserService {
// 用checkUser()来判断用户是否存在
public boolean checkUser(User user) {
boolean b = false;
// 使用SqlHelper来完成查询任务
String sql = "select * from user where username=? and password=?";
String parameters[] = { user.getUsername(), user.getPassowrd() };
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
// 根据rs来判断该用户是否存在
try {
if (rs.next()) {
b = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return b;
}
public ArrayList getUserByPage(int pageNow, int pageSize) {
ArrayList<User> arr = new ArrayList<User>();
// 查询sql
//String sql = "select * from user where id>3 order by id limit 20";
String sql="select sql_calc_found_rows * from user limit 0,10";
ResultSet rs = SqlHelper.executeQuery(sql, null);
// 二次封装 把 ResultSet -->User对象-->Arraylist(集合)
try {
while (rs.next()) {
User u = new User();
try {
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassowrd(rs.getString(3));
// 一定记住 u-->ArrayList
arr.add(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return arr;
}
public int getPageCount(int pageSize) {
String sql = "select * from user";
int rowCount = 0;
ResultSet rs = SqlHelper.executeQuery(sql, null);
try {
rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rowCount = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return (rowCount - 1) / pageSize + 1;
}
//删除用户
public boolean deleUser(String id){
boolean b=true;
String sql="delete from user where id=?";
String parameters[]={id};;
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
//用过id获取用户数据
public User getUserById(String id){
User user=new User();
String sql="select * from user where id= ?";
String parameters[]={id};
ResultSet rs=SqlHelper.executeQuery(sql, parameters);
try {
if(rs.next()){
user.setId(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassowrd(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return user;
}
//修改用户
public boolean updateUser(User user){
boolean b=true;
String sql="update user set username=?,password=? where id=?";
String parameters[]={user.getUsername(),user.getPassowrd(),user.getId()+""};
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
}
Replace this:
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
With:
ResultSet rs = SqlHelper.executeQuery(sql, parameters);

How to fix a DB probblem in Java (with DERBY DB)?

try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/gledi", "root", "root");
String sql = "SELECT MAX(NR) from ROOT.GLEDI";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
String nr1= rs.getString("MAX(NR)"); // here is the whole problem !!!!! how can i fix it
text.setText(nr1);
}
} catch (Exception e) {
}
Give it a name and look it up.
Is that column a String type or a number?
Empty catch blocks are wrong. Print or log the stack trace. You'll never know if an exception is thrown otherwise.
Sure you don't want select count(*) from root.gledi? This query looks wrong to me.
You don't close Connection, Statement, or ResultSet in a finally block, as you should.
You should encapsulate this code in a method and give it a Connection, not create it every time.
So little code, so many errors.
Here's how I might write it:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JdbcDemo
* #author Michael
* #link http://stackoverflow.com/questions/21205161/how-to-fix-a-db-probblem-in-java-with-derby-db/21205183#21205183
* #since 1/18/14 9:51 AM
*/
public class JdbcDemo {
private static final String SELECT_MAX_ROW_NUMBER = "SELECT MAX(NR) as maxnr from ROOT.GLEDI";
private Connection connection;
public JdbcDemo(Connection connection) {
this.connection = connection;
}
public String getMaxRowNumber() {
String maxRowNumber = "";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(SELECT_MAX_ROW_NUMBER);
rs = ps.executeQuery();
while (rs.next()) {
maxRowNumber = rs.getString("maxnr");
}
} catch (Exception e) {
e.printStackTrace(); // better to log this.
maxRowNumber = "";
} finally {
close(rs);
close(ps);
}
return maxRowNumber;
}
// belongs in a database utility class
public static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace(); // better to log this
}
}
// belongs in a database utility class
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace(); // better to log this
}
}
}

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