Hi,
I am using the below code in USER DEFINED JAVA CLASS:
//STEP 1. Import required packages import java.sql.*;
import org.pentaho.di.core.database.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL ="jdbc:mysql://localhost:1111/mysql";
// Database credentials
static final String USER = "USER";
static final String PASS = "PASS";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null; try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "select id,sorname,src_databasetype,src_databasename from table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String sorname = rs.getString("sorname");
String src_databasetype = rs.getString("src_databasetype");
String src_databasename = rs.getString("src_databasename");
//Display values
System.out.print("ID: " + id);
System.out.print(", sorname: " + sorname);
System.out.print(", src_databasetype: " + src_databasetype);
System.out.println(", src_databasename: " + src_databasename);
}
rs.close(); }catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace(); }catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace(); }finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample
Running the code through command prompt its working fine
BUT on running the step(In PDI) alone I am getting error:
Non-abstract class "Processor" must implement method "boolean org.pentaho.di.trans.steps.userdefinedjavaclass.TransformClassBase.processRow(org.pentaho.di.trans.step.StepMetaInterface,
org.pentaho.di.trans.step.StepDataInterface) throws
org.pentaho.di.core.exception.KettleException"
For UDJC, I think instead of putting code in the main method, you need to put it in processRow().
Instead of using -
public static void main(String[] args)
use -
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
I am still skeptical if its still going to work as I don't understand what you're trying to do with that code.
Try writing your code in processRow method as follows:
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException{
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
//String row = getString(r)+",";
//setValue(outputRow, row)
putRow(data.outputRowMeta, outputRow);
return true;
}
Related
I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}
I am trying to retrieve the value of a TEXT field from a table in a MySQL database.
MySQL version is 5.6.21
& I am using mysql-connector-java-5.1.18-bin.jar
My file is given below
import java.sql.*;
public class DatabaseConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/book";
// database credentials
static final String USER = "username";
static final String PASS = "password";
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...");
stmt = conn.createStatement();
String query;
query = "Select b_name, description columns from brands";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String first_name = rs.getString("b_name");
String description = rs.getString("description");
System.out.println(first_name);
System.out.println(description);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
} catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
} catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
This says that my column does not exist although I have tried this on another table, it works on VARCHAR columns but not on TEXT columns
This error shows up:
But the table has a column named description:
The problem is NOT about the column type being text.
You can get the value of a TEXT type using getString.
You can verify in the documentation.
The problem is in the query:
query = "Select b_name, description columns from brands";
"columns" there is a mistake.
Written this way, the description column is in fact renamed to columns in your result set.
If you did rs.getString("columns") you would get the value.
But that's not what you want to do. You want to fix the query by dropping that word:
query = "Select b_name, description from brands";
I am working with a java, SQL, swing JFrame project. I am new to programming and I've been trying to solve this problem for hours without any success.
The program I am trying to create is supposed to connect to my database (which is working) and then display the data from SQL database into a jtable - which is not working 100%.
Right now, the only thing that prints on the Jtable are the number "0". If I create a "Sout" the right info is printed in the normal NetBeans output.
I don't get an error, so the problem is quite complex. Thanks for your time=)
My first thread here! Sorry for the mess.
THE PROBLEM: I don't get the correct output from my database to my Jtable. The right output should be USER related output e.g Name, telephone number - Not "0 0 0"
DATABASE
public ArrayList<Kund> kundlista()throws ClassNotFoundException,
SQLException{
ArrayList<Kund> kundlista11 = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
System.out.println("Connecting to database...");
conn2 = DriverManager.getConnection("jdbc:sqlserver://milledb.database.windows.net:1433;database=Javamille;user=mille#milledb;password={Jagheter12};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
stmt2 = conn2.createStatement();
String sql2;
sql2 = "SELECT * FROM Kund";
ResultSet rs2 = stmt2.executeQuery(sql2);
Kund kund;
//STEP 5: Extract data from result set
while(rs2.next()){
int Kund_TeleNr = rs2.getInt("Kund_TeleNr");
int Kund_Pnr = rs2.getInt("Kund_Pnr");
String Kund_Fnamn = rs2.getString("Kund_Fnamn");
String Kund_Enamn = rs2.getString("Kund_Enamn");
System.out.print("Kundens telenr: " + Kund_TeleNr);
System.out.println("Kundens efternamn: " + Kund_Pnr);
kund=new Kund(rs2.getInt("Kund_Telenr"), rs2.getInt("Kund_Pnr"), rs2.getString("Kund_Fnamn"), rs2.getString("Kund_Enamn") );
kundlista11.add(kund);
}
//STEP 6: Clean-up environment
rs2.close();
stmt2.close();
conn2.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
return kundlista11;
}
}
SWING/UI class
public class KundUI extends javax.swing.JFrame {
/**
* Creates new form KundUI
*/
public KundUI() {
initComponents();
}
public ArrayList<Kund> lista;
public ArrayList<Kund> kundlista() throws ClassNotFoundException{
ArrayList<Kund> kundlistan = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn2 = null;
Statement stmt2 = null;
System.out.println("123.");
System.out.println("Connecting..");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn2 =
DriverManager.getConnection("jdbc:sqlserver://milledb.database.windows.net:1433;database=Javamille;user=mille#milledb;password={Jagheter12};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
//STEP 4: Execute a query
System.out.println("Hämtar kunder...");
stmt2 = conn2.createStatement();
String sql2;
sql2 = "SELECT * FROM Kund";
ResultSet rs2 = stmt2.executeQuery(sql2);
Kund kund;
//STEP 5: Extract data from result set
while(rs2.next()){
//Retrieve by column name
int Kund_TeleNr = rs2.getInt("Kund_TeleNr");
int Kund_Pnr = rs2.getInt("Kund_Pnr");
String Kund_Fnamn = rs2.getString("Kund_Fnamn");
String Kund_Enamn = rs2.getString("Kund_Enamn");
System.out.print("Kundens telenr: " + Kund_TeleNr);
System.out.print("Kundens förfanmn: " + Kund_Fnamn);
System.out.println("Kundens efternamn: " + Kund_Enamn);
System.out.println("Kundens efternamn: " + Kund_Pnr);
kund=new Kund(rs2.getInt("Kund_Telenr"), rs2.getInt("Kund_Pnr"), rs2.getString("Kund_Fnamn"), rs2.getString("Kund_Enamn") );
kundlistan.add(kund);
}
//STEP 6: Clean-up environment
rs2.close();
stmt2.close();
conn2.close();
}catch(SQLException e){
//Handle errors for JDBC
JOptionPane.showMessageDialog(null, e);
}
return kundlistan;
}
public void visa_kunder() throws ClassNotFoundException{
DefaultTableModel model = (DefaultTableModel)KundInfoUI.getModel();
Object[] row = new Object[4];
for(int i=0;i<lista.size();i++){
row[0]=lista.get(i).getTelenr();
row[1]=lista.get(i).getPnr();
row[2]=lista.get(i).getFnamn();
row[3]=lista.get(i).getEnamn();
model.addRow(row);
}
}
MAIN
package javaprojekt;
import java.sql.SQLException;
import java.util.ArrayList;
public class JavaProjekt {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Databas data = new Databas();
BabbeJonas loginGui = new BabbeJonas();
loginGui.setVisible(true);
KundUI kundUiT = new KundUI();
while (loginGui.password1234 == false){
System.out.println("Hej");
}
if(data.login(loginGui.getUserName(), loginGui.getPassWord()) !=
true){
// databasen hämtar kunder
ArrayList<Kund> kundlist; // Lista som finns i MAIN
kundUiT.lista= (ArrayList<Kund>)data.kundlista().clone();
kundUiT.setVisible(true);
for(int i = 0; i < kundUiT.lista.size(); i++) {
System.out.println(kundUiT.lista.get(i).getPnr());
}
while(true){
}
}
}
}
you can fill your table with this line of code:
KundInfoUI.setModel(DbUtils.resultSetToTableModel(rs2));
I have written a simple JDBC program to do a query and trying to create the prepared statement, but the result set is coming as empty. But when the same query executed through general statement creation gives the output and also through SQL plus.
package com.aexp.balu.jdbc;
import java.io.Reader;
import java.sql.*;
public class SimpleConnection {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String url="URL";
// String uname="uname";
// String pass="password";
String url = "URL";
String uname = "uname";
String pass = "password";
String query = "select CARD_NO from MDC.CAS_UNMCH_ROCS where CARD_NO = ?";
String cardNumber = "3222222222222222223";
try {
// step1 load the driver class
System.out.println("registering the driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
// step2 create the connection object . We need to have the type of
// connection
// The DriverManager class has a method get connection which give
// sthe instance of Connection
System.out.println("creating the connection....");
Connection con = DriverManager.getConnection(url, uname, pass);
// step3 create the statement object
System.out.println("creating the statement");
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, cardNumber);
// step4 execute query -- the stmnt object of the method execute
// query results an object
// of result set
System.out.println("Executing the query");
ResultSet rs = stmt.executeQuery();
System.out.println("After Executing the query");
while (rs.next()) {
System.out.println(" in reading result set");
String cardnumber = rs.getString("CARD_NO");
System.out.println(cardNumber);
}
// step5 close the connection object
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output is like this:
registering the driver
creating the connection....
creating the statement
Executing the query
After Executing the query
I have used jdbc driver before.But for this piece of program i can't connect to the db.This doesn't throw any exception or anything. Just won't connect. I couldn't find a solution online either.Below is the code i tried to run :( Please help in solving this. Thank you in advance :)
public class HeapMySql<T extends Comparable<T>> implements HeapInterface {
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Heap";
static final String USERNAME = "root";
static final String PASSWORD = "";
private int size = 0 ;
String sql;
static Statement stmt = null;
static Connection conn = null;
static ResultSet rs = null;
public void HeapMySql(){
try
{
sql = "CREATE TABLE testHeap (index integer, value integer);";
stmt.executeUpdate(sql);
System.out.println("Done");
}catch(Exception e){
}
}
public static void main(String [] arg){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database..."); //lets create a table in our database
stmt = conn.createStatement();
HeapMySql test1 = new HeapMySql<>();
}catch(ClassNotFoundException | SQLException ex){
}finally{
}
A constructor does not have a return type: docs
Remove void from public void HeapMySql() and it will do the work.
Also as said in comments, you should print the stacktrace in your catch blocks. This makes it easy to understand the exception and resolve the problem.