I am developing a simple app as a school project that is designed to be used by the client on his computer. I decide to use derby DB as it can work in embedded mode. However as everything works fine in eclipse, when I try to export it to executable jar file the app does not work properly.
I am trying to connect to DB and create tables if they don't exist as shown in the code. After the first launch of a jar new file named sampleDB appears on a screen so I guess that db is created. However, besides GUI components, the program does not work at all. I am executing those table methods in main as the first ones so I guess there may be something wrong with them, however, eclipse doesn't show any errors.
Here is a fragment of code responsible for connection and the creation of a table, that I mentioned.
public static Connection getConnection() throws Exception{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
conn = DriverManager.getConnection(URL);
return conn;
}catch(Exception e) {System.out.println(e);}
return null;
}
public static void table1() throws Exception {
Connection conn = getConnection();
try {
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("costs", conn)) {
String query= "CREATE TABLE costs("
+"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+"Name VARCHAR(60),"
+"value DOUBLE NOT NULL, "
+"driverdependent INT NOT NULL,"
+"costorpofit INT NOT NULL, "
+"fixedorvariable INT NOT NULL,"
+"driver VARCHAR(40),"
+"truck VARCHAR(40),"
+"semitrailer VARCHAR(40),"
+"Data TIMESTAMP,"
+"PRIMARY KEY (Id))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
static boolean doesTableExists(String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public static void table2() throws Exception {
try {
Connection conn = getConnection();
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("journeys", conn)) {
String query= "CREATE TABLE journeys("
+"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+"millage DOUBLE NOT NULL, "
+"driver VARCHAR(40),"
+"truck VARCHAR(40),"
+"semitrailer VARCHAR(40),"
+"Data TIMESTAMP,"
+"PRIMARY KEY (Id))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
public static void table3() throws Exception {
try {
Connection conn = getConnection();
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("routes", conn)) {
String query= "CREATE TABLE routes("
+"millage DOUBLE NOT NULL, "
+"Name VARCHAR(40))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
Related
I just started learning about MySQL and I am now trying to learn prepared statements. When I uses them, I get this error java.sql.SQLSyntaxErrorException. Can someone tell me where am I getting the syntax wrong? Thanks. Here is my code:
public class DBConnector {
private Statement statement;
private ResultSet result;
private PreparedStatement preparedStatement;
public void createDB() {
try {
sql = "CREATE DATABASE IF NOT EXISTS ?";
tableName = "test_name";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, tableName);
int myResult = preparedStatement.executeUpdate();
if(myResult == 1){
System.out.println("Database successfully created.");
}else{
System.out.println("Database with that name already exists. Please try again with different name.");
createDB();
}
}catch (SQLException e) {
System.out.println("Database creation failed.");
e.printStackTrace();
}
}
}
We can't bind Database names in Query parameters.
Statement stmt=con.createStatement();
int rs=stmt.executeUpdate("CREATE DATABASE dbname");
Try in this way, Database will create.
i am trying to run app that runs on both hsql and mysql database, to when i run it i get this error :
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.cnn" is null
at DataBase.DBcontrol.creer_piece(DBcontrol.java:122)
at pdr.FrontController.initialize(FrontController.java:160)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at pdr.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:832)
the chunck of code its reffering to in the first few lines are these :
public void creer_piece() throws ClassNotFoundException {
HConnexion dbc = new HConnexion(); cnn=dbc.connectDb();
PreparedStatement pss;
ResultSet s;
try {
req = "CREATE TABLE IF NOT EXISTS moussa.piece "
+ " (id VARCHAR(30), "
+ " atelier VARCHAR(30), "
+ " piece VARCHAR(30), "
+ " type VARCHAR(30) NULL, "
+ " pa VARCHAR(2) NULL, "
+ " ref1 VARCHAR(10) NULL , "
+ " ref2 VARCHAR(10) NULL , "
+ " quant INTEGER,"
+ " emp VARCHAR(30),"
+ " pos VARCHAR(30),"
+ " UNIQUE (id))";
pss = cnn.prepareStatement(req);
int e = pss.executeUpdate();
if (e > 0) {
JOptionPane.showMessageDialog(null, " erraurgg");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
and this one :
public void initialize(URL url, ResourceBundle rb) {
try {
run_wamp();
timer.schedule(new TimerTask() {
#Override
public void run() {
}
},10000);
dbc.creer_piece();dbc.creer_refs();dbc.creer_carte();dbc.creer_module();dbc.creer_eqip();
dbc.creer_c8();dbc.creer_secteur();dbc.creer_unite();dbc.creer_eqip();
dbc.creer_atelier();
dbc.get_natelier("SELECT * FROM moussa.atelier",combo_piece1);
} catch (Exception ex) {
Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
}
i think it has to do with my database, either the app is not creating the tables or i should create the tables manually and connect them, though i am just spit balling here, need some help please.
edit: so after looking at the comments, you guys told me that cnn is returning null because of the connectDB well here it is:
public class HConnexion {
private static String msg ;
Connection conn = null;Statement stm =null;
//=====================================================================================
public Connection connectDb() throws ClassNotFoundException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;";
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database
conn = DriverManager.getConnection(path, "root", ""); //mysql database
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa ");
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
this method (correct me if i am wrong) is supposed to connect me to my database (or create a new one in case there isn't any), so if cnn is returning null, does that mean that its not creating a database which the other methods can connect through cnn.
The null pointer exception is caused by your incorrect connection code which returns null.
// code for HSQLDB
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
// String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we leave this out as you can connect only to one database, not two
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
// Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - used
// conn = DriverManager.getConnection(path, "root", ""); //mysql database - unused
stm=conn.createStatement();
// stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}
If you want to connect to MySQL, use this code
// code for MySQL
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
// String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we use this for MySQL
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver");
Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - unused
conn = DriverManager.getConnection(path, "root", ""); //mysql database - used
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}
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());
}
}
}
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";
public static void main(String[] argv) {
try {
createTable();
insertRecordIntoTable("leo","123");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void createTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sequence = "CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20";
String createTableSQL = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(createTableSQL);
System.out.println(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
System.out.println("Table \"dbuser\" is created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
private static void insertRecordIntoTable(String username, String password) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO DBUSER1"
+ "(USER_ID, USERNAME, PASSWORD) VALUES"
+ "(ID_SEQ.NEXTVAL,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I cannot find the error when I try to create a sequence for my table.
When I try to insert some data in my table with the sequence it says it doesn't exist, but I did create it. Also I am not sure if i need a preparedStatement.setInt(1, seq_id.nextval); it gives an error but im not quite sure how I would do this
The solution might be adding the schema name (owner) before the name of sequence:
CREATE SEQUENCE some_nameOf_schema.ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20
You're preparing a statement with one SQL text, and executing the statement with two different SQL texts;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
...which is actually invalid according to the docs;
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
What you need to do is to prepare and execute two different statements;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate();
preparedStatement = dbConnection.prepareStatement(sequence);
preparedStatement.executeUpdate();
In general, it doesn't make much sense to CREATE database objects every time your application starts up, because this is something that's usually done only once, when you install/upgrade the database/schema the application uses.
However, if you really have to do it this way, the current solution could be improved so that the following points are considered:
Only execute the CREATE statements when the objects do not yet exist in the DB. This can be done by first inspecting the USER_OBJECTS data dictionary view.
Use a plain Statement instead of PreparedStatement for executing the DDL (prepared statements are only useful for DML operations that use input variables)
Handle JDBC resources (Connection / Statement / ResultSet) concisely and safely through the try-with-resources construct
Here's how the code could look like:
// query constants
private static final String CHECK_DB_OBJECT =
"SELECT 1 FROM user_objects WHERE object_name = ?";
private static final String CREATE_SEQUENCE =
"CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999" +
" MINVALUE 1 CACHE 20";
private static final String CREATE_TABLE = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
/* clip the main method etc. */
/**
* Creates the table and sequence only if they do not already exist.
*/
private static void createTableAndSequenceIfAbsent() {
try (Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
PreparedStatement ps = dbConnection
.prepareStatement(CHECK_DB_OBJECT)) {
if (!dbObjectExists(ps, "ID_SEQ")) {
executeDDL(dbConnection, CREATE_SEQUENCE);
}
if (!dbObjectExists(ps, "DBUSER1")) {
executeDDL(dbConnection, CREATE_TABLE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean dbObjectExists(PreparedStatement ps,
String objectName) throws SQLException {
ps.setString(1, objectName);
ResultSet rs = ps.executeQuery();
// if the #CHECK_DB_OBJECT query returned a row, the object exists
return rs.next();
}
private static void executeDDL(Connection c, String sql)
throws SQLException {
try (Statement st = c.createStatement()) {
st.execute(sql);
}
}