In my application, I am writing data to a database.
This is the code for database writing.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseRollback {
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("PostgreSQL JDBC Driver Registered!");
try {
dbConnection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/MyDB","root","123");
if (dbConnection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return dbConnection;
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println(e.getMessage());
e.printStackTrace();
}
return dbConnection;
}
public static void main(String args[]) throws SQLException {
Connection dbConnection = null;
PreparedStatement pstmt = null;
String query = "insert into orders(orderid, execid, exectype, lastprice, lastqty, ordstatus) values(?, ?, ?, ?, ?, ?)";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
pstmt = dbConnection.prepareStatement(query); // create a statement
pstmt.setString(1, "OrderID");
pstmt.setString(2, "Test02");
pstmt.setString(3, "exectype");
pstmt.setDouble(4, 100.00);
pstmt.setInt(5, 100);
pstmt.setString(6,"ordstatus");
pstmt.executeUpdate();
dbConnection.commit();
query.concat("error");
dbConnection.prepareStatement(query);
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
} catch (Exception e) {
// e.printStackTrace();
dbConnection.rollback();
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
}
}}
After debug point reach to the dbConnection.commit(); I have checked database and one record was inserted. But then it goes through dbConnection.rollback(); section. but it doesn't rollback inserted record. How can I implement rollback machanism?
dbConnection.commit();
should be placed at the end of your transaction.
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
dbConnection.commit();
} catch (Exception e) {
Related
So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}
I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}
we have customer provide architecture where they have use i series DB (green screen) and we have DB testing in scope for the contract. can some one help me to get more idea on how and which tool will be best fit for automation of these controls.
Thanks in Advance.
I suggest you to explore the possibilities of the java jdbc architecture to access and retrieve values from the database. You can use the the retrieved values to validate. :)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseConnections {
private Connection connection = null;
public Connection getDBConnectionQKB9() {
System.out
.println("DATABASE CONNECTION - Oracle JDBC Connection initialization");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, password);
if (connection != null) {
System.out
.println("DATABASE CONNECTION - Gained control - QKB9 database");
} else {
System.out
.println("DATABASE CONNECTION - Failed to make connection - QKB9 database");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void getData() {
try {
PreparedStatement pt= connection.prepareStatement(query);
ResultSet rs = pt.executeQuery();
while (rs.next()) {
//insert code to validate
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeDBConnection() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I'm new to JDBC and SQL and I have this program but when I run it, I get the following error:
java.sql.BatchUpdateException: Field 'stu_id' doesn't have a default value.
I have tried manipulating the line
pst = con.prepareStatement("insert into student(first_name,last_name,address) values (?,?,?)");
by adding a 4th question mark in values, and by adding stu_id in insert into student(). However, they have only given other errors. I don't know what to do?
package java11;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class PreparedExample {
public static void main(String[] args) {
Connection con=null;
PreparedStatement pst=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","Sree7rama3**");
pst = con.prepareStatement("insert into student(first_name,last_name,address) values (?,?,?)");
for(int i=1;i<=20;i++){
//pst.setInt(1, i);
pst.setString(1, "Hello-"+i);
pst.setString(2, "World-"+i);
pst.setString(3,"HYD-"+i);
pst.addBatch();
}
pst.executeBatch();
System.out.println("Update is successful!");
}catch (SQLException e) {
System.out.println("There are some SQL errors!");
e.printStackTrace();
}catch (ClassNotFoundException e) {
System.out.println("Driver class is not attached to this project!");
e.printStackTrace();
}finally{
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
it looks like when you added stu_id to you statement presumably you added this line
pst.setInt(1, i);
and you had these lines
pst.setString(1, "Hello-"+i);
pst.setString(2, "World-"+i);
pst.setString(3,"HYD-"+i);
So you were overwriting the first parameter (both 1).
try
pst = con.prepareStatement("insert into student(stu_id,first_name,last_name,address) values (?,?,?,?)");
pst.setInt(1, i);
pst.setString(2, "Hello-"+i);
pst.setString(3, "World-"+i);
pst.setString(4,"HYD-"+i);