Issue implementing embedded Derby database in eclipse project? - java

I'm trying to create a table, insert into the table and print the contents of the table using Derby (as shown below).
TestProject class:
package com.user.DerbyTest;
public class TestProject {
public static void main(String[] args) {
DBConnection db = new DBConnection();
db.createTable();
db.insertIntoTable("todd", 23, 'M');
db.insertIntoTable("wayne", 54, 'M');
db.printAll();
}
}
DBConnection class:
package com.user.DerbyTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private static final String DRIVER = "org.apache.derby.jdbc.*";
private static final String JDBC_URL = "jdbc:derby:derbytest;create=true";
Connection conn;
public DBConnection(){
try {
this.conn = DriverManager.getConnection(JDBC_URL);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (this.conn != null){
System.out.println("Connected to database.");
}
}
public void createTable(){
try {
conn.createStatement().execute("Create TABLE MyDerbytable(Name varchar(50), Age INT, Gender char(1))");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertIntoTable(String name, int age, char gender){
try {
conn.createStatement().execute("INSERT INTO MyDerbytable Values ("+name+","+age+","+gender+")");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printAll(){
try {
Statement statement = this.conn.createStatement();
ResultSet res = statement.executeQuery("Select * FROM MyDerbytable");
while(res.next()){
System.out.println(res.getString("Name") + res.getString("Age") + res.getString("Gender"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm getting a whole plethra of errors when trying to to run this:
Any ideas?
EDIT: Changing to DROP errors:

Your table already exits. Try DROP TABLE myderbytable;

Your first INSERT statement will end up being:
INSERT INTO MyDerbytable Values (todd,23,M)
You have no quotes around the todd and M values so there are treated as references to column names giving you the error you see. You must enclose literal values like this in single quotes:
INSERT INTO MyDerbytable Values ('todd',23,'M')
So your insert code might be:
"INSERT INTO MyDerbytable Values ('"+name+"','"+age+"','"+gender+"')"
(Note extra ' characters).
But concatenating strings like you are doing leaves you wide open to SQL Injection Attacks. It will also give you problems if any of your input contains a quote character. Learn about using PreparedStatement.

Related

Can't connect to hsqldb using jdbc java

I've got problem with connection to hsqldb using jdbc in java app. After parsing in main class from json to java I get 3 objects in list which i am trying to save to database.
Here is Dao class
public class EventDao {
private static final String URL = "jdbc:hsql:file:C:/Applications/appName//APPFOLDER";
private static final String USER = "sa";
private static final String PASS = "";
private Connection connection;
public EventDao() {
try {
Class.forName("org.hsqldb.jdbcDrive");
connection = DriverManager.getConnection(URL, USER, PASS);
} catch (ClassNotFoundException e) {
System.out.println("Couldnot establish connection");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void save(Event event) {
final String sql = "insert into event(id,state,timestamp,type,host,alert) values (?,?,?,?,?,?)";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, event.getId());
preparedStatement.setString(2, event.getState());
preparedStatement.setString(3, event.getTimestamp().toString());
preparedStatement.setString(4, event.getType());
preparedStatement.setString(5, event.getHost());
preparedStatement.setString(6, event.getAlert().toString());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
And here is main when i am trying to save object Event to db (the list have 3 objects)
public static void main(String[] args) {
EventParser eventParser = new EventParser();
eventParser.mainLoop();
}
public void mainLoop() {
try {
EventDao eventDao = new EventDao();
Map<String, EventWrapper> eventsFromFile = readEventsFromFile();
List<Event> eventsToSave = calculateEventTime(eventsFromFile);
for (Event event : eventsToSave) {
eventDao.save(event);
}
eventDao.close();
System.out.println(eventsFromFile);
} catch (IOException e) {
e.printStackTrace();
}
}
After debuging i found out that connection is null. Any ideas why?
The correct form of the URL is:
URL = "jdbc:hsqldb:file:C:/Applications/appName/APPFOLDER";
The Class.forName("org.hsqldb.jdbcDrive") ensures the HSQLDB jar is on your classpath and loads the JDBC driver class form the jar. This was done without error. The error message indicates there is no driver available for the incorrect jdbc:hsql:file url.

What is the best way Loading XML data to mySql using Java?

I am already working on a project to optimize interactions with dataBases using JAVA.
First Step , I began with loading XML data to mysql.
I found many articles working on this issue , and they parse Data before inserting it , like this article :
https://dzone.com/articles/load-xml-into-mysql-using-java
But I tried to do things simpler : so
I write this code that load data using LOAD local XML infile .. ( an sql Query ) and it works well .
package my.project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class App {
static final String dbUrl = "jdbc:mysql://localhost/dbOptimization";
static final String password = "azerty";
static final String user = "root";
public Connection conn;
/*
* Load jdbc Driver
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Dirver loaded");
} catch (ClassNotFoundException ex) {
System.err.println("Cannot load driver " + ex);
}
}
/*
* Connect to DB
*/
public void connect() {
try {
conn = DriverManager.getConnection(dbUrl, user, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
}
}
/*
* Create Table and Load Data
*/
public void createTable() {
try {
conn.createStatement().execute("create Table badges(Id INTEGER,UserId VARCHAR(20),Name varchar(20),Date DATE ,Class INTEGER ,TagBased VARCHAR(20))");
System.out.println("table created");
conn.createStatement().execute("Load xml local infile '/home/lenovo/Bureau/Project/3dprinting/Badges.xml'into Table badges(Id,UserId,Name,Date,Class,TagBased)");
System.out.println("data parsed");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("connot create Table" + e);
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
App app =new App();
app.connect();
app.createTable();
}
}
So please , Is there any problem with my code .?!
What are the pros and cons of each method ?
which one has a better performence ?
Thanks
The answer depends on whether or not you're going to use the XML as a whole document or not.
If you use XPath to search inside the document parsing and loading might make sense.

Java and SQL Server

I am new to java, and I am trying to create a method that will retrieve information from the database based on the query that will pass to it.
I thought that I could create by method by creating an object of type:
private Connection controlTableConnection = null;
and then
Statement statement = controlTableConnection.createStatement();
but when I do that piece of code, I get a highlight error:
Unhandled exception
Any help, would be appreciated.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ConnectMSSQLServer {
private static final String db_connect_string = "jdbc:sqlserver://Cdsx\\SQxxs";
private static final String db_userid = "aa";
private static final String db_password = "bb";
private Connection controlTableConnection = null;
public void dbConnect() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection controlTableConnection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception e) {
e.printStackTrace();
}
}
public void dbDisconnect() {
try {
if (controlTableConnection != null && !controlTableConnection.isClosed()) {
controlTableConnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void createstatement() {
Statement statement = controlTableConnection.createStatement();
}
}
You have to wrap the createStatement line like below, as you have to handle the SQLException.
try {
Statement statement = controlTableConnection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
isn't the Connection null? Do you have a driver on the classpath? is the default port correct? Is the sql server live? What kind of exception do you get exactly?
You need to post at least the stack trace or logs

Java : How to ignore some SQLException?

I'm trying to drop some objects in Oracle database using jdbc. I want to skip if specific ORA-04043 error occurs. The followings are the code I built.
This array string variable is SqlList.uninstall_OS_COMMAND_SQL.
public static String[] uninstall_OS_COMMAND_SQL = {
"DROP PACKAGE OS_COMMAND",
"DROP PACKAGE LOB_WRITER_PLSQL",
"DROP TYPE OSCOMMAND_VC2_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ENTRY",
"DROP TYPE FILE_LIST_TYPE",
"DROP TYPE FILE_TYPE",
"DROP PACKAGE FILE_PKG",
"DROP JAVA SOURCE \"OS_HELPER\"",
"DROP JAVA SOURCE \"FILE_TYPE_JAVA\"",
"DROP PACKAGE FILE_SECURITY"
};
and this is the code.
private void uninstallOS_COMMAND_Step1_For_11g() {
Connection targetDBconn = null;
Statement stmt = null;
try {
targetDBconn = globalTargetConn.connect();
logWriter.writeLogs(logTextArea, LogWriter.INFO, "Uninstalling OS_COMMAND package...");
for (int i = 0; i < SqlList.uninstall_OS_COMMAND_SQL.length; i++) {
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
logWriter.writeLogs(logTextArea, LogWriter.INFO, "See the query below...");
logWriter.writeLogs(logTextArea, LogWriter.INFO, "\n"+SqlList.uninstall_OS_COMMAND_SQL[i]);
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
}
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (stmt != null ) try {stmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
If I run this code, it executes just one item in the array and stops the entire method. Please help me..
Create one new method and call the new method inloop
Like
execute(Statement stmt, SQL Command ) throws Exception {
try {
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
} catch(SQLException s) {
//LOG error
if (s.getMessage().contains("ORA-04043")) {
} else {
throw s;
}
} catch (Exception ee) {
throw ee;
}
}
you might consider to put your try and catch inside the loop.

Java newbie needs help in database connection

I'm new to Java and even newer to java database connections. I've managed to create a database connection and query a table when I put it in the Main class. Now that I've moved it into a new class called Connection I am getting errors:
package lokate;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class Connection {
private static Statement stmt = null;
private static ResultSet rs = null;
private static Connection con = null;
public Connection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/Lokate?" +
"user=root&password=";
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
retriveData("SELECT * FROM Users");
int rowsEffected = 0;
} catch (SQLException sqlEx) {
System.out.println("SQL Exception: "+ sqlEx.toString());
} catch (ClassNotFoundException classEx) {
System.out.println("Class Not Found Exception: "+ classEx.toString());
} catch (Exception Ex) {
System.out.println("Exception: "+ Ex.toString());
}
}
public static void retriveData(String SQL) throws Exception {
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("fname") + " : " + rs.getString("lname"));
}
}
}
I'm getting an error saying cannot find symbol. Symbol:method createStatement() and incomparable types for con = DriveManager.....
Can anyone help?
Also, is it best practice to put the connection in the class like this then call a new object every time I want to do something with the db?
Regards,
Billy
I'd say your code is an example of many worst practices. Let me count the ways:
Your Connection class is a poor abstraction that offers nothing over and above that of java.sql.Connection.
If you use your class, you'll never get to take advantage of connection pooling.
You hard wire your driver class, your connection URL, etc. You can't change it without editing and recompiling. A better solution would be to externalize such things.
Printing an error message in the catch blocks is far less information than supplying the entire stack trace.
Your code hurts my eyes. It doesn't follow the Sun Java coding standards.
Your retrieveData method is utterly worthless. What will you do with all those printed statements? Wouldn't it be better to load them into a data structure or object so the rest of your code might use that information?
It's rowsAffected - "affect" is the verb, "effect" is the noun. Another variable that's not doing any good.
You're on the wrong track. Rethink it.
I think you'll find this code more helpful.
package persistence;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DatabaseUtils
{
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
}
Your problem is that DriverManager.getConnection returns a java.sql.Connection. Since your class is also called Connection you are getting a name clash between lokate.Connection and java.sql.Connection. You Will need to specify the fully qualified class name where ever you want to use java.sql.Connection, otherwise lokate.Connection is assumed.
Specify fully qualified class name like so:
java.sql.Connection con = null;
// ....
con = DriverManager.getConnection(connectionUrl);
Alternatively, rename your Connection class to something else and you will not get this naming conflict.
Connection is an existing type in the java.sql package, which is what DriverManager.getConnection returns. You have named your class as Connection too, so this is causing the confusion. The simplest way out would be to rename your class to something else and add an import java.sql.Connection; at the top.
Also, is it best practice to put the connection in the class like this then call a new object every time I want to do something with the db?
I think the best practice would be to use an existing solution to this problem, so that you can avoid re-inventing the wheel and focus on what makes your problem unique.
If you are writing a server application (it isn't clear whether you are), then I would also consider using a database connection pool. Creating new database connections on the fly is not efficient and doesn't scale well. You can read about database connection issues in this article I wrote a while back.

Categories