Querying a database via a constructor - java

I'm really hopping some help from anyone who would be kind enough to help me resolve this. I've been at it since yesterday.
See, what I'm trying to do is create a database query class that I can re-use over and over again as many times as possible without having to write a query every other time I need to search or display items from the database.
I'd like to be able to pass the query specifications via a constructor.
I however, get this error:
run:
Connecting to a selected database...
Connected database successfully...
Creating statement...
org.h2.jdbc.JdbcSQLException: Data conversion error converting ; SQL statement:
This is my code so far:
import java.sql.*;
public class RsToAList {
private final String table;
private final String columns;
private final String whereColumn;
private final String equalsEntry;
public RsToAList (String columns, String table, String whereColumn, String equalsEntry) {
this.table = table;
this.columns = columns;
this.whereColumn = whereColumn;
this.equalsEntry = equalsEntry;
}
// JDBC driver name and database URL
static String JDBC_DRIVER = "org.h2.Driver";
static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
static String USER = "sa";
static String PASS = "";
public static void main (String[] args) {
RsToAList tryAndGet = new RsToAList("fullNames", "CLIENT", "postOfficeBoxNumber", "6448");
tryAndGet.ourQueryMethod();
}
public void ourQueryMethod () {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String first = rs.getString(columns);
// Display values
System.out.print("ID: " + first);
}
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
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
}
I'm a JAVA/ Programming newbie, and I'm trying to teach myself how to code from home in case my question seems too simple, or I seem to have overlooked something in my code.
Edit:
I'm not sure if this could help you help me, but this is the class that creates the database table:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(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 table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} 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

Looks like a error in your sql statement.Make sure the data type you are comparing is compatible.PreparedStatement is handy instead of concatenating queries.
PreparedStatement stm = conn.prepareStatement("select * from person where name=?");
stm.setString(1,"ABC");
ResultSet rs= stm.executeQuery();

Although you have not shared the column type for the where condition. But most proabably you may be passing a string value to where clause but not enclosing it in single quotes:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
change it to:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" ='"+ (equalsEntry) +"'";
The other potential candidate for defect is this statementn:
String first = rs.getString(columns);
It may throw an error if any of your column type is not VARCHAR

Related

Why doesn't my Java code create a table in an in-memory SQLite database and print the table name?

I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

Why does Bluemix dashDB operation throws a SqlSyntaxErrorException with SQLCODE=-1667?

I'm getting this error even though I am not trying to edit the table/column:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: The operation failed because the operation is not supported with the type of the specified table. Specified table: "DASH103985.wajihs". Table type: "ORGANIZE BY COLUMN". Operation: "WITH RS".. SQLCODE=-1667, SQLSTATE=42858
#MultipartConfig
public class DemoServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(DemoServlet.class.getName());
private static final long serialVersionUID = 1L;
#Resource(lookup="jdbc/db2")DataSource dataSource;
private String getDefaultText() {
TweetsCombined = new String(" ");
try {
// Connect to the Database
Connection con = null;
try {
System.out.println("Connecting to the database");
} catch (SQLException e) {
TweetsCombined = "first" +e;
}
// Try out some dynamic SQL Statements
Statement stmt = null;
try {
stmt = con.createStatement();
String tableName = "wajihs";// change table name here to one
// chosen in the first website
String columnName = "msgBody";// msgBody is where the tweets
// are stored
String query = "SELECT * FROM \"" + tableName + "\"";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
content = rs.getString(columnName) + ". ";
if (content.toLowerCase().contains("RT".toLowerCase())
|| content.toLowerCase().contains("Repost: ".toLowerCase())) {
// do nothing
}
else {
TweetsCombined.concat(content);
}
}
// Close everything off
// Close the Statement
stmt.close();
// close
con.commit();
// Close the connection
con.close();
} catch (Exception e) {
TweetsCombined = "second" +e;
System.out.println(e.getMessage());
}
} catch (Exception e) {
TweetsCombined = "third" + e;
System.out.println(e);
}
return TweetsCombined;
}
As I explained here, dashDB, with its BLU Acceleration features, has certain limitations compared to DB2 without BLU Acceleration. In your case it is that you can only run queries with the CS isolation level against column-organized tables.
Either change your connection configuration to use CS isolation level or create your table(s) while explicitly specifying ORGANIZE BY ROW.

JAVA JDBC SQL updating a new database based on the old database records

I am trying to write a runnable jar file that can be able to connect to 2 different databases informix old database and oracle new database. It should be able to update the new database(oracle) with the old database(informix) records.
I re-edit my java code I added separate methods for my select, update and connections I am not getting an error but its not updating my db. My select works but my update statement is not working. This is my result i get - SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE where profile_id = 102
profileid : 102
ingressflag : Y
egress_flag : Y
ceingressflag : Y
ceegressflag : Y
ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
I am not sure how can I fixed the ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
public class TestConnection {
static ResultSet rs;
public static void main (String[] args) throws Exception {
try{
selectRecordsIcore();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE";
try {
dbConnection = getInformixConnection();
statement = dbConnection.createStatement();
System.out.println(selectTableSQL);
// execute select SQL stetement
rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
System.out.println("profileid : " + profileid);
System.out.println("ingressflag : " + ingressflag);
System.out.println("egress_flag : " + egress_flag);
System.out.println("ceingressflag : " + ceingressflag);
System.out.println("ceegressflag : " + ceegressflag);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ArrayList<TempStorageRecords> updateSQL = new ArrayList<TempStorageRecords>();
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
String updateTableSQL = "UPDATE traffic_profile SET ingress_flag = " + ingressflag
+ " ,egress_flag = " + egress_flag
+ " ,ce_ingress_flag = " + ceingressflag
+ " ,ce_egress_flag = " + ceegressflag
+ " WHERE profile_id = " + profileid + ";";
try {
dbConnection = getOracleConnection();
statement = dbConnection.createStatement();
System.out.println("updateTableSQL 1 :" + updateTableSQL);
// execute update SQL stetement
statement.execute(updateTableSQL);
System.out.println("updateTableSQL 2: " + updateTableSQL);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
}
public static Connection getOracleConnection() throws SQLException {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#oracle_host:1521:BIDS";
String username = "username";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Oracle driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
public static Connection getInformixConnection() throws SQLException {
String driver = "com.informix.jdbc.IfxDriver";
String url = "jdbc:informix-sqli://informix_host:1615/icore:INFORMIXSERVER=icit";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Informix driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
At first try to export data from source database into text file.
Your code uses hard coded column names, but I think it could read table names to export from some config file and column names from metadata from SELECT * FROM [table_name]. In JDBC there is getMetaData() for RecordSet. Use it.
When you export data into text files without problems you can do the next step: import such data directly from the source database to the destination database.
For destination database create prepareStatement with:
'INSERT INTO ' + table_name_dest + ' (' + column_names +') VALUES ('+ question_marks + ')'
(there question_marks are '?' chars which maps to columns).
Then for each record from source table and for each record (row) do:
insert_stmt.setObject(i, rs_in.getObject(i))
For big tables you can also use setFetchSize() and addBatch()/executeBatch()

USER defined java class step in pentaho data integration

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;
}

Inserting data into a database - org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:

I've been trying to save values into a database called "CLIENT".
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(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 table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255), " +
" CARD VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} 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
The class that I'm trying to have save into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public final String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} 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
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
StringBuilder builder = new StringBuilder();
String listStringClient = "";
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
return listStringClient;
}
I get an error message:
run:
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
I've been at this for the past two days to no success whatsoever. I will be very, very very greatful to anyone who would come to my rescue. Thank you.
This is where one problem is:
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
Values should be the getValues() method, instead of just a string, so
String sql = "INSERT INTO CLIENT VALUES (" + getValues() + ")";
Additionally, since you do not specify which columns, it is assumed that all columns are being entered in the values. If CARD does not have a default value in your SQL database, and if it cannot be NULL, you're going to have a problem.
Finally, this is a little strange:
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
You'll want the values, not 'NULL', so it should be
for (String s : client)
{
listStringClient += "'" + s + "'" + ",";
}
And finally, the way you're doing it, you're going to have an extra comma at the end (ex: 'value1','value2','value3',)
Clip the final comma:
return listStringClient.substring(0, listStringClient.size() - 1);
Granted, there's a better way to do the for loop where you do not have that extra comma.
End the end, the sql String should look like this:
"INSERT INTO CLIENT VALUES('value1','value2','value3','value4','value5','value6')"
Do a System.out.println(sql) and see what the String statement is that you're trying to execute. You'll see the error then.
Here's a better way to build your values string without the comma issue:
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
You forget to mention the value for CARD column. If you dont want to set any value there, just pass ' '.
Your for loop should be like this
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";//GIVES YOU ERROR BECAUSE AT THE END OF
} // FOR LOOP IT HAS , IN THE END OF STRING.
listStringClient+="' '";//This is for CARD COLUMN.
You do not pass any value in your statement. Following code is static, it does not have parameters:
INSERT INTO CLIENT " + "VALUES ((values))
It is nonsense SQL command: INSERT INTO CLIENT VALUES ((values)). You wanted express
String sql = "INSERT INTO CLIENT VALUES " + getValues()";
I prefer to use PreparedStatement, as it is safe and it will escape dangerous characters:
String sql = "INSERT INTO PRODUCT VALUES(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "asdf");
prest.setInt(2, 2009);
// etc
int count = prest.executeUpdate();
I think instead of :
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
You want something like :
String sql = "INSERT INTO CLIENT " + "VALUES ("+getValues()+")";
Also the implementation of getValues is kind of strange :
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
Probably it could be :
for (String s : client)
{
listStringClient += "'" + s + "',"
}
listStringClient += "NULL";
I can't thank you all enough for the amazing answers. I put the various ideas and came up with this solution to my problem.
My working answer to my Question above takes ideas from Leos Literak, abmitchell, Vimal Bera and Grisha's answers.
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(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 table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} 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
The class that saves into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public static String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT VALUES (NULL, " + (values) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} 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
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
}

Categories