Does anyone know what the best way is to create a new oracle database connection. This is what I currently have:
private static getConnection() throws Exception {
if (!isDriverRegistered){
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
isDriverRegistered = true;
}
return DrvierManager.getConnection(connectionString);
}
You are not supposed to register the driver yourself; the JDBC driver itself will do that, when its class is loaded. So, do not call DriverManager.registerDriver yourself.
There are two steps: make sure the JDBC driver class is loaded, and get a connection.
To load the JDBC driver class, use a line like this:
Class.forName("oracle.jdbc.OracleDriver");
Then get the connection with a call to DriverManager.getConnection:
Connection conn = DriverManager.getConnection(connectionString);
Note that if you are using a newer JDBC version and a suitable driver, you do not even need to load the driver class explicitly; it will be found and loaded automatically (via Java's service discovery mechanism). In that case you only need to call DriverManager.getConnection.
this class may help you
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCHelper {
public static void close(Statement obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(Connection obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static Connection getConnection()
{
Connection con = null;
String url = "url" //give url
String pwd = "password";//give password
String uid = "userId";//give userid
try
{
Class.forName("oracle.jdbc.OracleDriver"); //pass driver name
con = DriverManager.getConnection(url,uid,pwd);
con.setAutoCommit(false);
}
catch(Exception e)
{
if(con!=null)
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return con;
}
}
Related
I wrote this code but it doesn't work.
It throws an error that says that this is not suitable Driver.
Can anyone explain what I am doing wrong?
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionUtil {
public static Connection getConnection() {
try {
Class.forName("org.h2.jdbc.Driver");
Connection con = DriverManager.getConnection("org.h2:database/javadb", "root", "");
return con;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
I used this URL for a connection to my DB "jdbc:h2:file:./database/mydatabase"
I am developing an application using Swing, so before starting up I need to know a few basics regarding working with Connection. In many tutorials, I have seen that we need to create a connection Class and get the connection within the project using getConnection().
But I have created a connectionMethod is it possible to get the connection in my entire project by creating object of the connection class and using the connection?
This is my code:
package ncl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Test {
Connection connection=null;
public void connectionMethod() {
try {
Class.forName("org.h2.Driver");
connection=DriverManager.getConnection("jdbc:h2:~/test","sa", "");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test().connectionMethod();
try {
// DO STUFF HERE
} catch (Exception e) {
// TODO: handle exception
}finally {
try {
new Test().connection.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
I want to know whether this approach is good or not.
This totally depends on the practitioner that how he/she wants to code. Ideally we should follow Design Patterns in implementation to achieve many properties like Low Coupling, High Cohesion etc.
You told that in many tutorials, they make separate class which only provides connection. It is a good practice to avoid the problem of dependency and we can allocate responsibility to the classes in more efficient way. So you should also do it by creating new class which only provides the connection.
For the mentioned code, you have made some mistakes. You have first taken an instance of Test class which has connection and you didn't assign it to any variable. So you can't use it further when you need the connection. Another mistake is that you try to close the connection by creating another instance of Test class which obviously doesn't have started connection.
So, you can make appropriate suggested changes.
ConnectionFactory.java :
This will provide the connection objects.
package ncl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
Connection connection=null;
public void connectionMethod() {
try {
Class.forName("org.h2.Driver");
connection=DriverManager.getConnection("jdbc:h2:~/test","sa", "");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test.java :
Write the actual code here.
package ncl;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
ConnectionFactory connectionObject = new ConnectionFactory();
connectionObject.connectionMethod();
try {
// DO STUFF HERE
} catch (Exception e) {
// TODO: handle exception
}finally {
try {
connectionObject.connection.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
You can use below utility class :
public class MyConnection {
private Connection con = null;
public Connection getConnection() {
try {
if (con == null) {
Class.forName("org.h2.Driver");
con = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
}
For getting connection you can call MyConnection().getConnection();
For example :
If you want to get connection in any class then do the following :
Connection con = new MyConnection().getConnection();
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
I have the following Java 7 code to create a CachedRowSet.
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
Is there a way to get the Connection object from the CachedRowSet object? I would like to set autoCommit to false on the Connection object before invoking the acceptChanges() on CachedRowSet as I'm getting the following exception when invoking acceptChanges().
javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true
There is a COMMIT_ON_ACCEPT_CHANGES field on CachedRowSet, but it's Deprecated.
Well, it took some time for me to reproduce the issue at my end. Setting the autoCommit value of the Connection to false via conn.setAutoCommit(false); resolved this issue.
Following is the sample working program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
public class CRSetChecker {
public static void main(String[] args) {
String connectString = "jdbc:oracle:thin:scott/tiger" +
"#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)" +
"(HOST=myorahost)(PORT=5521))" +
"(CONNECT_DATA=(SID=myorasid)))";
//Get DB connection
Connection conn = (new CRSet()).getConnection(connectString);
if (conn == null) {
System.out.println("Connection failed");
System.exit(0);
} else {
System.out.println("Connection established successfully!");
try {
CachedRowSet crs =
RowSetProvider.newFactory().createCachedRowSet();
String query="select ename from emp";
crs.setCommand(query);
crs.execute(conn);
//Set auto commit false
conn.setAutoCommit(false);
int count = 0;
while(crs.next()){
String name = crs.getString(1);
count++;
System.out.println(name);
if(count==1){
crs.updateString(1, "COOPER");
crs.updateRow();
crs.acceptChanges(conn);
System.out.println("After update:"+crs.getString(1));
}
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public Connection getConnection(String connectString)
{
Connection con = null;
try {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection(connectString);
} catch (SQLException ex) {
ex.printStackTrace();
}
return con;
}
}
Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}