I spend like 5 hour re-writing all methods cause thought i make mistake while inserting data into DB BUT i noticed everything is fine when i got database outside src folder.
This is my code
public class DataBaseModel {
public static final String DRIVER = "org.sqlite.JDBC";
// public static final String DB_URL = "jdbc:sqlite::resource:sqlite/databse.db"; // insider src/sqlite
public static final String DB_URL = "jdbc:sqlite:database.db";
private Connection conn=null;
private Statement stat=null;
public DataBaseModel() {
try {
Class.forName(DataBaseModel.DRIVER);
} catch (ClassNotFoundException e) {
System.err.println("NO JDBC DRIVER");
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(DB_URL);
stat = conn.createStatement();
} catch (SQLException e) {
System.err.println("Connection problem");
e.printStackTrace();
}
createTables();
}
When i got my project setup like that:
public static final String DB_URL = "jdbc:sqlite:database.db";
everythin work fine:
creating records
display records form db
creating tables
But when i change to
public static final String DB_URL = "jdbc:sqlite::resource:sqlite/databse.db";
there is an error
Connection problem java.sql.SQLException: resource sqlite/database.db not found: java.net.MalformedURLException: no protocol: sqlite/database.db
I get rid of error unconsciously by copping database to src/sqlite thats why i was unable to see any error for all that time ...
Any idea what cause problem when database.db is inside src/sqlite?
I explained as much as i can.
Thx for help
Related
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.
I'm wondering if anyone can shed some light on this topic, as I have been racking my brain for days and can't quite understand why this does not work. I have three classes
main, RetrieveDBVersion,GetOracleConnection I've been doing some testing with oracle JDBC, UCP and Java 1.7.
According to the Oracle documentation, If I use connection pooling the connection will be returned to the pool as soon as I close the connection, Invalidate it and set it to null See Here. So I decided to give it a whirl and see if it would perform just like the documentation says it should. In my Main application I have a simple loop which makes a connection 200 times by calling RetrieveDBVersion. RetrieveDBVersion is simply performing a query and returning the driver version. My loop works fine until I hit the magic number of 68 and then I receive an error which states
java.sql.SQLException: Exception occurred while getting connection:
oracle.ucp.UniversalConnectionPoolException:
Cannot get Connection from Datasource: java.sql.SQLException:
Listener refused the connection with the following error:
ORA-12516, TNS:listener could not find available handler with matching protocol stack
These are the detail of the 3 methods. These methods are not in a server environment. They are simply calling a local oracle express database and I'm running them from my desktop. Why would I keep getting this error? If I'm returning the connections back to the pool?
Main
import com.jam.DB.JDBCVersion;
import static java.lang.System.out;
public class MainApp {
public static void main(String[] args) {
String myMainJDBCVar;
try{
for(int i=1; i<200; i++ )
{
myMainJDBCVar= JDBCVersion.RetrieveDBVersion();
out.println(myMainJDBCVar + " " + i);
}
out.println("this is Done!");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
RetrieveDBVersion
import java.sql.*;
import oracle.ucp.jdbc.ValidConnection;
public class JDBCVersion {
public static String DBVersion;
public static String RetrieveDBVersion()throws SQLException {
Connection conn = JDBCConnection.GetOracleConnection("test");
try {
DatabaseMetaData meta = conn.getMetaData();
//get driver info
System.out.println("JDBC driver version is " + meta.getDriverMajorVersion());
DBVersion = meta.getDriverVersion();
} catch (SQLException e) {
e.printStackTrace();
DBVersion = e.getMessage();
}
finally {
System.out.println("hit the finally clause");
((ValidConnection) conn).setInvalid();
conn.close();
conn=null;
}
return DBVersion;
}
GetOracleConnection
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;
import java.sql.*;
public class JDBCConnection {
public static Connection GetOracleConnection(String Enviroment) throws SQLException{
PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();
Connection conn = null; //ora.defaultConnection();
try {
pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:#//localhost:1521/xe");
pds.setUser("system");
//pds.setInitialPoolSize(5);
pds.setPassword("xxx");
pds.setMaxStatements(10);
conn = pds.getConnection();
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return conn;
}
So after careful though and getting a little extra help from the Oracle forum. I finally understand why the above referenced code is giving the error message that I'm receiving. See Here For Response
Because I'm setting the data source everytime the loop goes around, I'm essentially creating more than one pool. The way to do this, is create one pool and than pull connections from that pool.
New code to replace the GetOracleConnection I created a singleton class for datasource and in code I simply retrieve the connection from the data source like such
Connection conn = Database.getInstance().GetPoolSource().getConnection();
package com.jam.DB;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;
public class Database {
private static Database dbIsntance;
private static PoolDataSource pds;
private Database() {
// private constructor //
}
public static Database getInstance() {
if (dbIsntance == null) {
dbIsntance = new Database();
}
return dbIsntance;
}
public PoolDataSource GetPoolSource() {
if (pds == null) {
pds = PoolDataSourceFactory.getPoolDataSource();
try {
pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:#//localhost:1521/xe");
pds.setUser("system");
pds.setPassword("xxxx");
pds.setMaxStatements(15);
return pds;
} catch (Exception e) {
}
return pds;
}
return pds;
}
}
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
I'm trying to understand JDBC API and in order to do so,I'm just writing some code to estabilish a connection to the DB. It seems that I can't...
I'm trying to manually load the Driver for mysql DB,but even if I include the connector .jar in the classpath the compiler complains that it can't find the package com.mysql.
If,on the other hand,I omit the Class.forName() method, the code compiles but I get a hundreds Exception lines at runtime.
I'm compiling (and running) including the jar in the command line:
javac -cp [path to jar] DBTest.java
here's my code:
import java.sql.*;
class DBTest {
**strong text**
static final String ADDRESS="jdbc:mysql://127.0.0.1:8888/customer";
static final String USER="myuser";
static final String PASSWORD="luca";
public static void main(String[] args) {
Connection conn=null;
Statement stat=null;
Class.forName("com.mysql.jdbc.Driver");
try {
conn=DriverManager.getConnection(ADDRESS,USER,PASSWORD);
stat=conn.createStatement();
String query="SELECT * FROM person";
ResultSet result=stat.executeQuery(query);
while (result.next()) {
String name=result.getString("name");
String surname=result.getString("surname");
int id=result.getInt("id");
String telephone=result.getString("telephone");
System.out.println(id+": first name: "+name+" second name: "+surname+" tel: "+telephone);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
conn.close();
stat.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Edit:
with the double quotes it now compiles fine, but at runtime it says something like:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Replace
Class.forName(com.mysql.jdbc.Driver);
with
Class.forName("com.mysql.jdbc.Driver");
I am new to Java and NetBeans, and I am attempting to create a form that
connects to a database using JDBC connection
reads information from seven columns and displays them on a jTable component already on the form
I already have this working. I am now trying to optimize my code and use a better architecture to separate the database connection and the user interface (UI forms) code so that I can have a separate class to perform the connection and then simply call the method from this class in the code behind the button. The problem with using NetBeans and forms is that I don't know where to instantiate this class and such. Below is a cope of the class that I have created to perform the JDBC connection
public class ConnectionManager {
private static String url = "jdbc:mysql://localhost:3306/prototypeeop";
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = "root";
private static String password = "triala";
private static Connection con;
private static String url;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
This is already a .java file. I have a JForm, and I need to call this method behind the button. Here is how I do it in the form currently without using a connection class:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
String sql="Select * from eopdata";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/prototypeeop","root","jakamuga");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String Year=rs.getString("Year");
String Month=rs.getString("Month");
String Day=rs.getString("Day");
String MJD=rs.getString("MJD");
Double xarcsec=rs.getDouble("xarcsec");
Double yarcsec=rs.getDouble("yarcsec");
Double UT1UTCsec=rs.getDouble("UT1UTCsec");
model.addRow(new Object[] { Year, Month, Day, MJD,xarcsec,yarcsec,UT1UTCsec});
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
How can I use the class instead of hard coding in the connection? I have already created the class but where do I instantiate it. Do I do it in the main of the form or do I do it in the actionevent code with the following code?
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
con = ConnectionManager.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
To literally answer your question: your getConnection method is a public static method so you can call this from anywhere. Just call ConnectionManager.getConnection() where-ever you need that connection.
Some other remarks about your code:
You shouldn't query a database in the actionPerformed method. This method is called on the EDT, and doing a database query and looping over the results is a long-running task. Doing this task on the EDT will block your UI. Consult the Concurrency in Swing tutorial for more info about Swing and threading
Consider caching the Connection object
Do not forget to close your resources. If I remember correctly, a ResultSet must be closed afterwards. Do this in a finally block