Using savepoints with the JDBC-ODBC Bridge: UnsupportedOperationException - java

I have connected NetBeans IDE with MS Access and while doing a transaction I got this error.
It seems that savepoints are not supported...Please guide me..
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cse");
Statement stmt1, stmt2, stmt3;
System.out.println("Statements created");
conn.setAutoCommit(false);
String query1 = " update registration set id='105' " +
"where first = 'Sumit' ";
String query2 = " update registration set id='106' " +
"where first = 'Zayed' ";
System.out.println(" Queries created");
stmt1 = conn.createStatement();
System.out.println(" Connection created");
Savepoint s1 = conn.setSavepoint("sp1");
System.out.println(" Savept created");
stmt2 = conn.createStatement();
stmt1.executeUpdate(query1);
stmt2.executeUpdate(query2);
conn.commit();
stmt3 = conn.createStatement();
stmt1.close();
stmt2.close();
conn.releaseSavepoint(s1);
conn.close();
The error is
Statements created
Queries created
Connection created
Error: java.lang.UnsupportedOperationException

The JDBC-ODBC Bridge apparently does not support Savepoints at all. However, the UCanAccess JDBC driver does support unnamed Savepoints:
String connStr = "jdbc:ucanaccess://C:/__tmp/test.mdb";
try (Connection conn = DriverManager.getConnection(connStr)) {
conn.setAutoCommit(false);
try (Statement s = conn.createStatement()) {
s.executeUpdate("UPDATE ucaTest SET Field2='NEWVALUE1' WHERE ID=1");
}
java.sql.Savepoint sp1 = conn.setSavepoint();
try (Statement s = conn.createStatement()) {
s.executeUpdate("UPDATE ucaTest SET Field2='NEWVALUE2' WHERE ID=2");
}
conn.rollback(sp1);
conn.commit();
} catch (Exception e) {
e.printStackTrace(System.out);
}
For more information on using UCanAccess see
Manipulating an Access database from Java without ODBC

Related

I am trying to connect my java application to hostinger.in(but no output)

I am trying to connect my java application to hostinger.in
I tried this code but no output is displayed.Is this code correct
enter code here
Class.forName(\"com.mysql.jdbc.Driver\");
conn = DriverManager.getConnection(\"jdbc:mysql://mysql.hostinger.in/u869878874_stock\" ,\"u869878874_stock\", \"bhavin\");
stmt = conn.prepareStatement(\"SELECT * FROM logintbl\");
ResultSet rs=null;
rs=stmt.executeQuery();
while (rs.next())
{
usr =usr+rs.getString(\"userid\");
}
jLabel1.setText(usr);
I tried this code but no output is displayed
Is this code correct
Stop using escape sequence in your code and start using string directly.
https://docs.oracle.com/javase/tutorial/java/data/characters.html
Ex.
Class.forName("com.mysql.jdbc.Driver")
Changes to your code.
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet resultSet = null;
String SELECT_SQL = "SELECT * FROM logintbl";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<host>:<port>/<database_name>", "<user id>", "<password>");
pStatement = connection.prepareStatement(SELECT_SQL);
resultSet = pStatement.executeQuery();
for(;resultSet.next();){
System.out.println("User Id " + resultSet.getString("userid"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}

MySQLSyntaxErrorException in SQL syntax

I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?

PSQLException thrown when trying to execute SELECT query

I have problem with my SQL request, when I run my request, I receive this message error:
org.postgresql.util.PSQLException: A result was returned when none was expected.
Here is my request:
Connexion con = new Connexion();
try {
c = con.Connect();
stmt = c.createStatement();
int sqlCalcul = stmt.executeUpdate(
"SELECT inventaire FROM calcul WHERE designation='" + designation +
"' AND date=(SELECT MAX(date) FROM calcul)");
stmt.close();
// c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
You should use executeQuery instead of executeUpdate:
ResultSet sqlCalcul = stmt.executeQuery("SELECT inventaire...")
executeUpdate is used for a INSERT, UPDATE, or DELETE statement, and will throw an exception if a ResultSet is returned. executeQuery should be used for SELECT statements.
Take a look at PostgreSQL's tutorial using the JDBC driver for more information.

In Java, How to Drop Sqlite Table

hi i have tried this command on my sqlite database but it wont drop/delete my database table,
here my reference
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE 'myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
//Output
output : 0
there are no return error so i still cant figure by myself what is making the code not working.
Code to Drop Table
Connection c = null;
Statement stmt = null;
String sql;
c = openSqlite(c); //method i create to setup sqlite database connection
stmt = c.createStatement();
try{
System.out.println("Deleting table in given database...");
String sqlCommand = "DROP TABLE 'myTable' ";
stmt.executeUpdate(sqlCommand);
System.out.println("Table deleted in given database...");
stmt.close();
c.commit();
c.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
Thanks to MadProgrammer and other, Actually i miss to put commit statement on my code..
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE IF EXISTS 'myDatabase.myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
stmt.close();
conn.commit(); // commit after execute sql command
//COMMIT TRANSACTION makes all data modifications performed since
//the start of the transaction a permanent part of the database,
conn.close();

Java prepared statement in try-with-resources not working [duplicate]

This question already has answers here:
How should I use try-with-resources with JDBC?
(5 answers)
Closed 8 years ago.
Yesterday multiple people on Stack recommended using try-with-resources. I am doing this for all my database operations now. Today I wanted to change Statement to PreparedStatement to make the queries more secure. But when I try to use a prepared statement in try-with-resources I keep getting errors like 'identifier expected' or ';' or ')'.
What am I doing wrong? Or isnt this possible? This is my code:
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1, user);
ResultSet rs = stmt.executeQuery()) {
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
A try-with-resource statement is used to declare (Autoclosable) resources. Connection, PreparedStatement and ResultSet are Autoclosable, so that's fine.
But stmt.setInt(1, user) is NOT a resource, but a simple statement. You cannot have simple statements (that are no resource declarations) within a try-with-resource statement!
Solution: Create multiple try-with-resource statements!
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
executeStatement(conn);
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
private void executeStatement(Connection con) throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id=? LIMIT 1")) {
stmt.setInt(1, user);
try (ResultSet rs = stmt.executeQuery()) {
// process result
}
}
}
(Please note that technically it is not required to put the execution of the SQL statement into a separate method as I did. It also works if both, opening the connection and creating the PreparedStatement are within the same try-with-resource statement. I just consider it good practice to separate connection management stuff from the rest of the code).
try this code:
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1, user);
ResultSet rs = pstmt.executeQuery())
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
note that here, resource is your Connection and you have to use it in the try block ()
Move
stmt.setInt(1, user);
ResultSet rs = stmt.executeQuery()
...within the try{ /*HERE*/ }
This is because stmt is the resource being created try (/*HERE*/) {} to be used try{ /*HERE*/ }
Try-with-resources
try (/*Create resources in here such as conn and stmt*/)
{
//Use the resources created above such as stmt
}
The point being that everything created in the resource creation block implements AutoClosable and when the try block is exited, close() is called on them all.
In your code stmt.setInt(1, user); is not an AutoCloseable resource, hence the problem.

Categories

Resources