I am Trying to write a stored procedure in derby Database.
I wrote a Java file which executes as expected.
This is my java File
package javaapplication8;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JavaApplication8 {
public static void procedure(int uid, String Domain) {
Connection con;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Love_To_Learn", "Mohammed_Numan", "mohammed");
String sql = "Update Intrests set Points = Points + 10 where User_Id = " + uid + " and Intrest = '" + Domain + "'";
PreparedStatement pst = con.prepareStatement(sql);
int x = pst.executeUpdate();
if (x == 1) {
System.out.println("Finally");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I installed the jar file in the database by using.
CALL sqlj.install_jar( 'C:\Users\flipkart\My Documents\NetBeansProjects\JavaApplication8\dist\JavaApplication8.jar', 'Mohammed_Numan.JavaApplication8',0);
And
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath','Mohammed_Numan.JavaApplication8');
Created a Procedure Using
CREATE PROCEDURE Final(IN ID INTEGER,
IN Dom VARCHAR(40))
LANGUAGE JAVA
PARAMETER STYLE JAVA
EXTERNAL NAME 'javaapplication8.JavaApplication8.procedure';
This gives me no error.
Now i called the Procedure Using
call Final(10006,'Java');
Even this executes.But the table is not Updated.
Any reason For This?
I even Called this using callable Statement.
The code is
CallableStatement cst = con.prepareCall("Call Final (?,?)");
cst.setInt(1,Integer.parseInt(u.getString(1)));
cst.setString(2,v.getString(1));
boolean done = cst.execute();
if(done){
System.out.println("Done")
}
else{
System.out.println("Sorry");
}
And i always get Sorry..!Where Am i Going Wrong?Please Check out.
Related
I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.
I've a table on PostgreSQL like this:
I want to running another Java .class by the content inside the DATA table.
If the content written FIT1, i want to run the FIT1.class;
So do if the content written FIT2, i want to run the FIT2.class; etc.
I only got my code below, and i think it's not work bcs when it tried to get the content, it got all the contents. So the IF function cant work.
Base on the table, i want to running all the process (7 data).
Is there any solution to fix the code?
package fit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class FIT {
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/FIT","admin", "admin");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM DATA;" );
while ( rs.next() ) {
String data = rs.getString("data");
System.out.println( "Data = " + data );
System.out.println();
if (data.equals("FIT1")){
FIT1.main(args);
}
else if (data.equals("FIT2")){
FIT2.main(args);
}
else{
}
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
instead check data == "FIT1" use equals
try this block code:
if (data.equals("FIT1")){
FIT1.main(args);
}
else if (data.equals("FIT2")){
FIT2.main(args);
}
I am doing practice for JDBC and using NetBeans 8.1. I created a table in MS Access and wrote a program. But the problem is that when I pass column index then my program runs successfully. But I pass column name as in my table in MS Access then there occurs an error that
Column not found
I am pasting code of my program and try to explain my problem further.
package database;
import java.sql.*;
public class Database {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:personDSN";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "SELECT *FROM students";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
String Name = rs.getString(2);
String add = rs.getString(3);
String pNum = rs.getString(4);
System.out.println(Name + " " + add + " " + pNum);
}
con.close();
}
catch(ClassNotFoundException | SQLException sqlEx)
{
System.out.println(sqlEx);
}
}
}
As you can see in while loop that i have passed column index in getString() function. In this case my program runs successfully. But when i pass name of field/attribute which is in my database table, then it gives me error that "Column not found". For example if I pass getString("name") then it gives me above error.
Please help me to solve my problem.
Note: I have checked again and again that there is no spelling mistake in my parameter opposite to actual table in ms access.
This question already has answers here:
MySQL LIMIT clause equivalent for SQL SERVER
(5 answers)
Closed 8 years ago.
I want to fetch some record(it can be 50,100 or something else that is configured by user) from database without using limit clause because our application may be work on multiple database like mysql,oracle,mssql,db2....
i did following solution
package com.test;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.util.Date;
public class BatchRetrieveTest extends Object {
private static final int FETCH_SIZE = 10;
public BatchRetrieveTest() {
}
public static void main(String[] args) {
BatchRetrieveTest batchRetrieveTest = new BatchRetrieveTest();
batchRetrieveTest.test();
}
void test() {
Connection conn = null;
Statement stmt2 = null;
Date start = null;
Date end = null;
int i = 0;
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root", "root");
stmt2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
conn.setAutoCommit(false);
stmt2.setFetchSize(FETCH_SIZE);
stmt2.setPoolable(true);
start = new Date();
System.out.println(new Date() + "second execute start"
+ new Date().getTime());
ResultSet rs2 = stmt2
.executeQuery("SELECT * FROM sample_final_attendance limit 1000");
end = new Date();
System.out.println(new Date() + "*************second execute end"
+ (end.getTime() - start.getTime()));
rs2.absolute(200000);
i = 0;
while (rs2.next()) {
if (i++ > 100) {
break;
}
}
rs2.close();
stmt2.close();
end = new Date();
System.out.println(new Date() + "second read end"
+ (end.getTime() - start.getTime()));
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stmt2.close();
conn.close();
} catch (Exception e) {
}
}
}
}
Here sample_final_attendance table contains 15 columns and 3.2 millions of record
while executing this program it requires 2GB of memory and 47 seconds of execution time
here i wonder that if some table has billions of record then it fails to execute
also i used setFetchSize as suggested but problem is same
please suggest some solution
thanks in advance
Well the ASFAIK & understood, the problem is more related with the handling of data in polyglot storage. If you think, you need to resolve the same in all cases interdependent of the database type - the one common approach is to build a serving layer .
The serving layer can be a cache library or even a Map of Maps created by you. Do not attempt to query the database with large number of records at once, instead bring the data as batches, and store it as a pool of pojos. On demand of the user, you can serve the data from the serving layer.
You can make use of the memcache or hazlecast or many other cache libraries, which can be directly integrated with databases. I really don't know how complex is your situation. What I made is a suggestion. This makes up a data-grid, which can be populated with data from any databases in the background.
We have setMaxRow(int numOfRow) in Statement Object this will limit number of rows generated by the Statement Object and simply ignore the remaining.
Take the look at the doc.
This question already has answers here:
java.sql.SQLException: No database selected - why?
(4 answers)
Closed 3 years ago.
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"
//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
public class DataBase {
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
// 2.open a data source name by means of the jdbcodbcdriver.
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
Statement stmt = con.createStatement();
// Shut off autocommit
con.setAutoCommit(false);
System.out.println("1.Insert 2.Delete 3.Update 4.Select");
Scanner s = new Scanner(System.in);
int x;
x = s.nextInt();
String query; // SQL select string
ResultSet rs; // SQL query results
boolean more; // "more rows found" switch
String v1, v2; // Temporary storage results
Vector<Object> results = new Vector<Object>(10);
if (x == 1) {
try {
stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
} catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
}
if (x == 2) {
try {
stmt.executeUpdate("DELETE from employee where emp_id='102' ");
}catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
if (x == 3) {
try {
stmt
.executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
} catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
query = "SELECT * FROM employee ";
try {
rs = stmt.executeQuery(query);
// Check to see if any rows were read
more = rs.next();
if (!more) {
System.out.println("No rows found.");
return;
}
// Loop through the rows retrieved from the query
while (more) {
v1 = "ID: " + rs.getInt("emp_id");
v2 = "Name: " + rs.getString("emp_name");
System.out.println(v1);
System.out.println(v2);
System.out.println("");
results.addElement(v1 + "\n" + v2 + "\n");
more = rs.next();
}
rs.close();
} catch (SQLException e) {
System.out.println("" + results.size() + "results where found.");
}
finally{stmt.close();}
}
public static void main(String[] args) throws SQLException {
String str = "y";
do {
DataBase s = new DataBase();
s.LoadDriver();
DataBase.connect();
Scanner sc = new Scanner(System.in);
System.out.println("DO u Want to PROCEED TO QUERY : ");
str = sc.next();
} while (str !="n");
}
}
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.
then
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
Statement stmt = con.createStatement();
...
Just from looking at the exception.. I would guess that you are not specifying the database.
How can you do a select on a table without telling it which schema to select from ?
This is typically set in the connection string..
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool?
If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter.
But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still.
while (str !="n")
That's not how you compare strings in Java.
Found a bug listing at MySQL that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well.
Some things that stick out as odd to me (although no clue if they will have any impact on your error)
You only need to load the Driver Manager once
You aren't closing your connection, so either close it or refactor to use the same one.
Perhaps move these two lines to just before the do loop
DataBase s = new DataBase();
s.LoadDriver();