resultset in JDBC SQL - java

I have a GUI JDBC SQL project. I can read the information from my Database well but i don't know what is wrong with my create,update,delete method. Seem like some methods in resultSet doesn't work correctly. My code is below.
public Person create(Person p){
try {
rs.moveToInsertRow();
rs.updateInt("PersonID", p.getPersonID());
rs.updateString("firstName", p.getFirstName());
rs.updateString("middleName", p.getMiddleName());
rs.updateString("lastName", p.getLastName());
rs.updateString("email", p.getEmail());
rs.updateString("phone",p.getPhone());
rs.insertRow();
rs.moveToCurrentRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}// end of create method
public Person update(Person p){
try {
rs.updateString("firstName", p.getFirstName());
rs.updateString("middleName", p.getMiddleName());
rs.updateString("lastName", p.getLastName());
rs.updateString("email", p.getEmail());
rs.updateString("phone",p.getPhone());
rs.updateRow();
rs.moveToCurrentRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}//end of update method
public void delete(){
try {
rs.moveToCurrentRow();
rs.deleteRow();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of delete method
thanks for your reading.
public PersonBean() {
try {
Class.forName(JDBC_DRIVER);
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
sm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = sm.executeQuery("Select * From Person");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of PersonBean
my connection to SQL is OK because i can read information from SQL but i cant write data to SQL. Here is my error when i try to create a new Person.
com.microsoft.sqlserver.jdbc.SQLServerException: The result set is not updatable.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.throwNotUpdatable(SQLServerResultSet.java:436)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyResultSetIsUpdatable(SQLServerResultSet.java:447)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.moveToInsertRow(SQLServerResultSet.java:4350)
at PersonBean.create(PersonBean.java:29)

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. An updatable result set allows modification to data in a table through the result set. The following code makes a result set that is scrollable and insensitive to updates by others:
try {
// Create a statement that will return updatable result sets
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//Primary key EmployeeID must be specified
//so that the result set is updatable
ResultSet resultSet = stmt.executeQuery(
"SELECT EmployeeID, Name, Office FROM employees");
} catch (SQLException e) {
}

You want to use following example and check this codes with your codes in project:
//database connector file example (com.mysql.jdbc.Driver)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String DB_URL = "jdbc:mysql://localhost:3306/dbname";
String DB_USER = root;
String DB_PASS = "";
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
Statement stmt = con.createStatement();
stmt.executeQuery("Select * From Person");
ResultSet resultSet = stmt.getResultSet();
while(resultSet .next()){
System.out.print(resultSet.getString("fieldName");
//and other your field to display
}
resultSet.close();
stmt.close()
} catch(Exceptoin e) {
....
}
There are many examples of this approach for insert, update and delete.

Related

Java - [SQLITE_BUSY] The database file is locked (database is locked)

I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)
I have these at start of my class;
private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
Methods for example;
public int lastPlaceProgram(){
String query= "Select * from userprogram where laststayed = 1";
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
int programid = 0;
while(rs.next()){
programid = rs.getInt("programid");
}
return programid;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
or
public String programType(int programid){
String query = "Select * from programs where id = ?";
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1, programid);
ResultSet rs = preparedStatement.executeQuery();
String type = "";
while(rs.next()){
type = rs.getString("type");
}
return type;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
And constructor;
public Operations() {
String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
try {
con = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
}
}
I tried to add these finally block to after catch blocks of all my 30 methods;
finally{
try{
con.close();
} catch(Exception e){
}
}
But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.
Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.

Trying to show info from database into terminal

I'm trying to display a list of the names of people in the database from the terminal, but not sure about how I would go about this. Right now I'm using a prepared statement
public static void showNames() throws SQLException {
Statement stmt=null;
Connection conn=null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String selectTable="SELECT * FROM userInfo;";
stmt.execute(selectTable);
}
You're close.
Below code is not a complete answer, but hopefully enough to get you moving in the direction of obtaining a complete answer. The below code is basically the code you posted with some modifications.
public static void showNames() throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
String selectTable="SELECT * FROM userInfo;";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
rs = stmt.executeQuery(selectTable);
while (rs.next()) {
Object obj = rs.getObject("name of column in database table USERINFO");
System.out.println(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
You didn't post the structure of database table USERINFO, so replace name of column in database table with the actual column name.
By the way, there are many examples of how to do this on the Internet, for example Processing SQL Statements with JDBC.

PreparedStatement staying null

I am currently creating a private method inside a servlet. But my PreparedStatement keeps returning null.
private ArrayList<String> emails(String id) {
ArrayList<String> email= new ArrayList<String>();
try {
PreparedStatement st = null;
ResultSet data = null;
DriverManager.getConnection(
"jdbc:postgresql://localhost/test",
"test", "test");
String sql = "SELECT email FROM hdpr.email_table WHERE id='"
+ id+ "'";
data = st.executeQuery(sql);
while (data.next()) {
email.add(data.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
e.getMessage();
}
return email;
}
Try it like this:
private ArrayList<String> emails(String id) {
ArrayList<String> email= new ArrayList<String>();
try {
PreparedStatement st = null;
ResultSet data = null;
// Creating a new connection
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost/test",
"test", "test");
// your SQL Query now with a ? as parameter placeholder
String sql = "SELECT email FROM hdpr.email_table WHERE id = ?";
// creating a new preparedStatement using your sql query
st = con.prepareStatement(sql);
// set the first ? to the value of id
st.setString(1, id);
data = st.executeQuery();
while (data.next()) {
email.add(data.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
return email;
}
Steps you should also have a look to:
If you assign null to a variable it will be null the NullpointerException will always occur if you try to call a method from that object.
To use your PreparedStatement st you need to initialize it by creating preparedStatement using your connection and also your SQL query.
Don't add parameters to a SQL query using the + operator - this will open doors for SQL Injection for this we have the prepared statement and setString(), setInt(), ...
You should have a look at tutorials like let's say this: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

Inserting into MySQL database using Prepared

I am using a PreparedStatement to insert into mysql,I get no error but data has not been inserted,when I check in the mysql console it says Empty set:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry)
{
PreparedStatement statement=null;
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
try {
conn.setAutoCommit(false);
statement=(PreparedStatement) conn.prepareStatement(sql);
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I also tried using a Statement like this and get this ERROR
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"',"+objkey+"');";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Your use of PreparedStatement never actually executes the statement. Change your code to:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry) {
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
conn.setAutoCommit(false);
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
statement.executeUpdate(); // <---- This is what is missing!
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have also included try-with-resources so that the statement is actually correctly closed.
the answer given by Mark is correct. that should help you inserting using prepared statement.
You Sql query for inserting using Statement is incorrect. you have missed the starting ' for objkey variable. the correct query is
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"','"+objkey+"');";

Java Class error in Eclipse

Giving error at line 12 "This method must return a result of type Boolean".
I have written my code in try catch block. If a move the resultset operation below the catch block then the error appears on resultset object.
Where am I wrong, Please answer me. Thank you.
public class LoginService {
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
return true;
} else {
System.out.println("User does not exists !!");
return false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When your code catches an exception you are simply printing the stacktrace and then allowing the function to continue.
However, after the catch blocks, you have no return statement, which is what the complaint is.
As others have mentioned, you're missing a return statement either in the catch blocks or after the catch blocks. Here's my boiler plate example of a function that returns a boolean:
bool foo()
{
bool result = false;
//do stuff, and set result to true at some point
return result;
}
This pattern is beneficial because it helps reduce the number of returns in your functions. There are some coding styles out there that won't allow more than 2 return statements in a function, for example.
Here it is applied to your function:
public Boolean verifyLogin(LoginModel loginModel) { // In this line it is
// giving error
Boolean result = false;
DbConnection dbConnection = new DbConnection();
ResultSet rs;
try {
Connection con = dbConnection.getConnection();
System.out.println("Connection Established");
String query = "select * from login where tenantid=? and userid=? and password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, loginModel.getTenantid());
ps.setString(2, loginModel.getUserid());
ps.setString(3, loginModel.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("User exists !!");
result = true; //--------------------This line changed!
} else {
System.out.println("User does not exists !!");
result = false; //-------------------This line changed!
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
You should return in catch blocks too. Or in finally block.
You need to add a return statement after your catch block.
Your method may throw an exception, in this case, the code that will be executed will be in the catch clauses.
Add a finally clause after the catch's with the desired value for when this happens.
The problem is that if an exception occurs, nothing is returned. I would suggest adding
return false;
to all of your catch blocks

Categories