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;
}
}
Related
This question already has answers here:
Solving a "communications link failure" with JDBC and MySQL [duplicate]
(25 answers)
Closed 3 years ago.
I'm making a Sign Up form and I made everything but still it wont connect. I hope someone here can help.
My myConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class myConnection {
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://turtlenetwork.net/contact" + "user=IDKLMAO&password=OkIKnowYouTriedButNOLOL");
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
return con;
}
}
SignUp
private void jLabelCreateMouseClicked(java.awt.event.MouseEvent evt) {
Connection con = myConnection.getConnection();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO `user`(`username`, `pass`, `mail`) VALUES (?,?,?)");
ps.setString(1, jTextField1.getText());
ps.setString(2, String.valueOf(jPasswordField1.getPassword()));
ps.setString(3, jTextField3.getText());
if (ps.executeUpdate() != 0) {
JOptionPane.showMessageDialog(null, "Account Created");
} else {
JOptionPane.showMessageDialog(null, "Failed");
}
} catch (HeadlessException | SQLException ex) {
Logger.getLogger(SignUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the error that I get when I run click the create button.
https://pastebin.com/ce44LYzW
It's supposed to write everything on the database and make that account.
Connect Java to a MySQL database
https://www.javatpoint.com/example-to-connect-to-the-mysql-database
Whenever you make a connection in java, you need to make sure to add in the username and the password with two coma's.
con = DriverManager.getConnection("jdbc:mysql://turtlenetwork.net/contact", "username", "password");
Make sure to separate user and password with a coma.
Also, check out DriverManager documentation here
https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html
I have managed to solve the issue on my own.
Here is the new myConnection.java
package ContactList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class myConnection {
// Init Database Constants
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/contact";
private static final String USERNAME = "NOPE";
private static final String PASSWORD = "NOPE";
private static final String MAX_POOL = "250";
// Init Connection Object
private Connection connection;
// Init Properties Object
private Properties properties;
// Create Properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// Connect Database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// Disconnect Database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
PreparedStatement prepareStatement(String insert_into_userusername_pass_mail_VALUES) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
And then there is the SignUp which I changed aswell.
private void jLabelCreateMouseClicked(java.awt.event.MouseEvent evt) {
myConnection con = new myConnection();
String sql = "INSERT INTO `user`(`username`, `pass`, `mail`) VALUES (?, ?, ?)";
try {
PreparedStatement ps = con.connect().prepareStatement(sql);
ps.setString(1, jTextField1.getText());
ps.setString(2, String.valueOf(jPasswordField1.getPassword()));
ps.setString(3, jTextField3.getText());
if (ps.executeUpdate() != 0) {
JOptionPane.showMessageDialog(null, "Account Created");
} else {
JOptionPane.showMessageDialog(null, "Failed");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.disconnect();
}
}
Thanks to everyone that tried to help.
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
This is my connetion class. i need to return resultset to specific class. but i found resultset is closed in that class. i use connectio pooling in my connection.
i want to create general connection class that manages all operations for database in my application.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class OpenTestConnection {
private DataSource dataSource=null;
private Connection connection=null;
private Statement statement=null;
public OpenTestConnection()
{
System.out.println("come in Openconnection....");
try {
// Get DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/ietddb");
} catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public ResultSet selectfromtable(String sql)
{
System.out.println("come here....");
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
try { if(null!=resultSet)resultSet.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=statement)statement.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=connection)connection.close();} catch (SQLException e)
{e.printStackTrace();}
}
return resultSet;
}
}
Well Shree has answered your issue. You have closed the ResultSet before returning it.
However, to add to what you are trying to achieve.
1) surround your return dataSource.getConnection in try catch.
2) Create seperate query function and connection close function like below
protected Connection connection = null;
protected Statement statement = null;
protected PreparedStatement prepared = null;
// executeQuery
protected ResultSet execute(String sql) throws SQLException {
connection = getConnection();
statement = connection.createStatement();
return statement.executeQuery(sql);
}
//now have a close function
protected void commitAndClose() {
if (connection != null) {
try {
connection.commit();
} catch (SQLException ex) {
// your code for handling ex
} finally {
try {
resultSet.close(); //do not know why you are closing resultset
statement.close();
connection.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
connection = null;
}
}
}
This will give you more flexibilty when your code expands.
It seems a very basic question but I couldn't find any resolution for it.
I have following code with me:
package com.test.db.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCConnect
{
private Connection conn = null;
private final String uname = "root";
private final String passwd = "test#123";
private String url = "jdbc:mysql://127.0.0.1:3306/TrainDB";
private final String className = "com.mysql.jdbc.Driver";
public void initConnection()
{
try
{
if(this.conn == null || this.conn.isClosed())
{
try
{
Class.forName (className).newInstance ();
this.conn = DriverManager.getConnection(url, uname, passwd);
System.out.println("database connection established.");
}
catch(SQLException sqe)
{
sqe.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
//return this.conn;
}
public void disconnect()
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
public void insertData(String sql)
{
PreparedStatement s;
try
{
if(conn == null || conn.isClosed())
{
initConnection();
}
s = conn.prepareStatement(sql);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
}
catch (SQLException e)
{
e.printStackTrace();
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception se) { /* ignore close errors */ }
}
}
}
public ResultSet query(String sql)
{
Statement s = null;
try
{
if(this.conn == null || this.conn.isClosed())
{
initConnection();
}
s = conn.createStatement();
s.executeQuery(sql);
ResultSet rs = s.getResultSet();
System.out.println("lets see " + rs.getFetchSize());
return rs;
}
catch(SQLException sq)
{
System.out.println("Error in query");
return null;
}
finally
{
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I am using JDBCConnect in a different class:
import java.sql.ResultSet;
import java.sql.SQLException;
public class traininfo
{
public static void main(String[] args)
{
JDBCConnect jdbcConn = new JDBCConnect();
String sql = "SELECT id FROM testtable";
ResultSet rs = jdbcConn.query(sql);
try {
System.out.println(rs.getFetchSize());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rs != null)
{
try
{
while(rs.next())
{
System.out.println(rs.getString("id"));
}
rs.close();
}
catch(SQLException sqe)
{
}
}
jdbcConn.disconnect();
}
}
I am not using concurrent calls for insertion and reads. If I use the same query in mysql-workbench (client), I am getting proper results but using the mentioned code, I am getting
database connection established.
lets see 0
0
Database connection terminated
Please suggest me what I am missing?
Most probably it's because you're closing Statement before you are using it's ResultSet. It's strange that it doesn't throw an exception, but this is not correct anyway.
As per Statement.close method JavaDoc:
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
I suggest to use some kind of callback to retrieve results from ResultSet before it's closed e.g.:
public <T> T query(String sql, IResultSetHandler<T> resultSetHandler ) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
final ResultSet rs = connection.executeQuery(sql);
final T result = resultSetHandler.handle(rs);
return result;
} finally {
if(statement != null) {
statement.close();
}
}
}
public interface IResultSetHandler<T> {
T handle(ResultSet rs);
}
public static void main(String[] args) {
JDBCConnect jdbcConn = new JDBCConnect();
List<String> ids = jdbcConn.query(sql, new IResultSetHandler<List<String>>() {
public List<String> handle(ResultSet rs) {
List<String> ids = new ArrayList<String>();
while(rs.next()) {
ids.add(rs.getString("id"));
}
return ids;
}
});
}
Or to use commons apache dbutils library which does exactly the same.
ResultSet.getFetchSize() lets you know the maximum number of rows that the connection will fetch at once. You can set it with ResultSet.setFetchSize(int). See also the official documentation. It does not tell you how many rows in total you will get. If the fetch size is left to zero, JDBC decides on its own.
Other than that, refer to Yura's answer which addresses the core of your problem.
Could it be because you never call InsertRows, as it never shows that 'X rows were inserted'
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;
}
}
}