Thread main Suspended - java

my code is given below and i hav created a user class also
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
// print the results
System.out.println(user);
usersList.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
new UserServicesDAO().get_all_data();
}
}
i got the output, only last_update gives me null value. I have changed it to timestamp but no effect...in the debug gives me error:
Thread main suspended
UserServicesDAO.get_all_data() line24
UserServicesDAO.main(String[]) line56
what's the problem plz give me a solution..

I see only two reasons for user.last_update to be null:
It's null in the database. Check your data. Check that everything is committed. Check that you're querying the correct database.
setLast_update() doesn't actually set the field last_update field. Show us the code of User to confirm or infirm.
Also, please respect the Java naming conventions.

I think the problem is with your database. Make sure resultSet is returning the right type.
For example:
resultSet.getInt("id");
might be
resultSet.getLong("id");
this can cause you troubles. At least this happened to me once. You should check for other fields name,email,mobile.
Also be careful about date
resultSet.getString("last_update")
if in your database "last_update" column type is not string, this can also cause you problems

Related

Cant make connection with MariaDB and Java

Im trying to create web app using java and mariadb but i encountered problem when tried to implement mariadb to login. Here my code:
initSql:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
#WebServlet("/initSql")
public class initSql extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public initSql() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
Connection conn = null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/baza_new", "root","root");
System.out.println("db povezana");
}catch(Exception e){
//JOptionPane.showMessageDialog(null, e);
System.out.println("db NIiiJE povezana");
//return null;
}
}
}
LoginDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.initSql;
public class LoginDAO {
static Connection con = null;
public static boolean validate(String username, String password, String type) {
boolean status = false;
try {
con = initSql.init();
System.out.println("1");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
//pst.setString(1, type);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
status= rs.next();
con.close();
}catch(Exception e) {System.out.print(e);}
return status;
}
}
and i get markers:
Cannot make static reference to non-static method from type generic servler
Type mistmatch cannot connect from void to Connection
I'm little bit stuck with this problem.Can someone help me with my code?
People seem to be neglecting the more broad-scale issues in your code. There are standards to follow like capitalization etc but overall you have some bigger issues.
You shouldn't be making erroneous instances of initSql as it's an HttpServlet, it just doesn't make sense. You also have static/non-static references to a Connection field when you don't need it. To start with, change initSql#init to return a Connection, and while I normally wouldn't recommend abusing static this way, make the method itself static:
//returns a connection, requires no class instance
public static Connection init(ServletConfig config) { ... }
From there, we can now retrieve a Connection instance by calling this method:
Connection con = initSql.init();
Overall you should have a proper class or design for handling this, but for simple learning this is "okay".
Secondly, you're not quite using ResultSet correctly. #next will determine if there is an available row to point to from the SQL results, and if so it moves the marker to the next row. You would use it in order to check if you can retrieve results:
ResultSet set = /* some sql query */;
String someField;
if (set.next()) {
//gets the value of the column "my_field"
someField = set.getString("my_field");
} else {
//no results!
someField = null;
}
Alternatively, if you were looking for multiple results you can loop over #next
while (set.next()) {
//just one value out of many
String myField = set.getString("my_field");
}
In this use-case it's alright to check if the row exists, but I would personally check against something like user permissions or somesuch. If you relied on code like this for something sensitive you might expose something you don't want to.
Overall, I would work a little more on your logical structure for the code, and maybe go over some of the basics for Java and common coding standards for it (Google and Oracle have good guides for this).
Firstly, your class name initSql should have Capitalized first letter to follow conventions.
Secondly, you should either create an instance/object of InitSql and then call the method init() on that object or make the init() method static.
initSql.init() isn't static, which is not a problem of MariaDB and its connection from Java :) To fix this error you can add static to the mentioned method. But: As there are multiple errors in your code (e.g. assigning the result of a void method to a variable), it will not work then either..

ucanaccess SQL Exception: invalid cursor state: identified cursor is not open

I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.

No success getting TextField values into database - JavaFx

I'm trying to save a TextField value into a database but I get the error:
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
INSERT INTO KIWI VALUES (104, ) [21002-173]
What I'd like to happen is to have a client's first name saved into the database when the 'addClient()' method is called.
Could anyone help me get it to work? Thank you all in advance.
I'm working in JavaFx and the 'TextField firstName' is being called from an FXML file that was created using JavaFx SceneBuilder. I've tried initializing it in the controller but no success. Any ideas? I thought these types of objects should not be innitialized, at least going by JavaFx rules as I understand.
The Controller Class:
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import wakiliproject.Forms.AddNew.DB.NewClientDB;
public class NewClientController implements Initializable {
#FXML
public TextField firstName;
// Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
public void addClient() throws SQLException {
new NewClientDB().main();
}
}
The database class:
import Database.Plain.Skell.DBConnect;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import wakiliproject.Forms.AddNew.NewClientController;
public class NewClientDB extends NewClientController {
private String firstNames = new NewClientController().firstName.getText();
public void main() throws SQLException {
Connection conn = DBConnect.connect();
Statement stmt = null;
try {
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO KIWI "
+ "VALUES (104, " + (firstNames) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}
Edit:
I don't think the TextField values are being picked
As a sidenote, you should use PreparedStatements. You'll avoid concatenation errors as well as SQL injection.
But your problem seems to come from the fact that you're getting the value before the user has had a chance to type anything there. I'm not familiar with JavaFX, but your current code is getting the textfield value at the beginning of the program (when it's obviously still empty). Shouldn't it perform the addition when you click a button or something?
There are so many things wrong here.
You cannot create a new controller class with a new statement and expect it to be the same instance as that created by an FXMLLoader. Delete this line:
private String firstNames = new NewClientController().firstName.getText();
NewClientDB should not extend NewClientContoller. The FXMLLoader knows nothing about subclasses.
Pass the firstName from your controller to your NewClientDB instance.
new NewClientDB().main(firstName);
....
public void main(String firstNames)
Place single quotes around the firstNames string in your insert statement.
"INSERT INTO KIWI VALUES (104, '" + (firstNames) + "')";
Ensure that your KIWI table only has two columns with types compatible to your insert statement.
Check your FXML supplies an fx:id for firstName.
Check that you have a button defined in your FXML which triggers #addClient.
If the above doesn't solve your problem, edit your question to include your KIWI table DDL and your FXML file.

Passing a Database query as an argument from jersey client to jersey webservice to perfom DML

I have a jersey client which needs to perform DML operation on a remote database server. I have created jersey web service which takes argument as a string(i.e. query to be passed by client). I don't know how should I do it. Please help me. Thanks in advance.!
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.ws.rs.Path;
import oracle.sql.CLOB;
#Path("/insertupdate")
public class InsertUpdate {
/**
* Inserts inclusion detail in Database
* #param insertQuery
* #param inclusionScript
*
*/
#Path("/insertInclusions")
public void insertInclusions(String insertQuery, String inclusionString) {
DbConnection con = null;
Connection conn = null;
PreparedStatement insertSt = null;
try {
con = new DbConnection();
conn = con.dbConnect();
insertSt = conn.prepareStatement(insertQuery);
CLOB tempClob = CLOB.createTemporary(conn, false,
CLOB.DURATION_SESSION);
tempClob.putChars(1, inclusionString.toCharArray());
insertSt.setClob(1, tempClob);
insertSt.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
// insertSt.close();
if (insertSt != null)
insertSt.close();
} catch (SQLException sqlExp) {
sqlExp.printStackTrace();
}
}
}
}
First you need to correct your web service code to accept the params. If you are using GET, then you can use PathParam to accept your DB query strings. Something liek this:
#Path("/insertInclusions")
public void insertInclusions(#PathParam("insertQuery") String insertQuery, #PathParam("inclusionString") String inclusionString)
In your jersey client code, you can simply add the params in the GET URL

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Conn.Connexion.insertUtilisateur(Connexion.java:50)

I want to insert some informations in my dataBase "sqlserver" via NetBeans!!!the connection is good but don't know what's the pb,realy this pb make me crazy!!!!!!!
Please help me!!!!
CODE:
package Conn;
import java.sql.Connection;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
1. #author Nadia
*/
public class Connexion {
java.sql.Connection C;
private Connection C1;
String Nom;
String Adresse;
String MDP;
String VMDP;
/**
* Constructeur`enter code here`
*/
public Connexion() {
//this.connection=ConnexionBDD.getInstance();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
C1=DriverManager.getConnection("jdbc:sqlserver://localhost\\A:1433databaseName=Authentif","sa","sqlserver");
Statement stmt = C1.createStatement();
}
catch(Exception e){}
}
//*************Insertion Utilisateur
// public int insertUtilisateur(UserIdentit utilisateur) {
public void insertUtilisateur(String Nom,String Adresse,String MDP,String VMDP) {
PreparedStatement pst;
try {
**pst = C1.prepareStatement("INSERT INTO Authentif.dbo.tab_authentif (Nomc,Adressec,MDP,VMDP)"+"VALUES(?,?,?,?)");** *(ligne 50)*
pst.setString(1,Nom);
pst.setString(2,Adresse);
pst.setString(3,MDP);
pst.setString(4,VMDP);
int res=pst.executeUpdate();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
Follow the SQL Server documentation
You need to add a semi-colon before the database key-value pair:
jdbc:sqlserver://localhost\\A:1433;databaseName=Authentif
^
This is causing the Connection to be null here. No exceptions message appears as the exception is being silently caught. Add some form of notification such as a printStackTrace call. Finally, catch the most specific exception, in this case, an SQLException. This allows the application to handle database specific exceptions.

Categories

Resources