SQLException executing query in Java SQLite - java

I have this class in my NetBeans project:
public class ConexionBD
{
private Connection conexion;
private Statement consulta;
private final String ruta;
private final String claseDriver;
private final String driver;
public ConexionBD(String ruta)
{
this.ruta = ruta;
this.claseDriver = "org.sqlite.JDBC";
this.driver = "jdbc:sqlite:";
}
public void conectar() throws SQLException, ClassNotFoundException
{
Class.forName(this.claseDriver);
this.conexion = DriverManager.getConnection(this.driver + this.ruta);
System.out.println("Opened database successfully");
this.consulta = this.conexion.createStatement();
System.out.println("Statement created successfully");
}
public ResultSet consultar(String sql) throws SQLException
{
ResultSet resultado = this.consulta.executeQuery(sql);
System.out.println(this.consulta.getConnection());
return resultado;
}
}
And this method which use it:
private void buildTableView()
{
ConexionBD c = new ConexionBD(System.getProperty("user.dir") + "bbdd");
ObservableList<ObservableList> data FXCollections.observableArrayList();
System.out.println(System.getProperty("user.dir") + "\\bbdd");
try
{
c.conectar(); //WORKS FINE
}
catch(ClassNotFoundException | SQLException e)
{
Constantes.showAlert(AlertType.ERROR, "Error", "Error de base de datos", "Error de conexión");
}
try
{
String sql = "select name from controller";
ResultSet rs = c.consultar(sql); //THROWS SQLException
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
row.add(rs.getString(1));
data.add(row);
}
reguladores.setItems(data);
}
catch(SQLException e)
{
Constantes.showAlert(AlertType.ERROR, "Error", "Error de base de datos", "Error al obtener los datos");
}
try
{
c.cerrar();
}
catch (SQLException ex)
{
Constantes.showAlert(AlertType.ERROR, "Error", "Error de base de datos", "Error al cerrar la conexión");
}
The connection method seems to work fine, but when it executes the method which calls the "executeQuery(sql)" method, it throws the SQLException.
I think I configured the jdbc driver, ojdbc library and database fine, but I can't find why the method doesn't do its job. Any clue?
The stack trace:
java.sql.SQLException: no such table: controller
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NestedDB.prepare(NestedDB.java:115)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89)
at app.ConexionBD.consultar(ConexionBD.java:37)
at app.controllers.InicioController.buildTableView(InicioController.java:145)
The table does exist in database

Try to fully qualify your table name like OWNER.TABLE_NAME
Make sure the account you connect with has SELECT privilege granted to it from the table owner
Those are my two obvious suggestions
Brute force is to examine all tables like so:
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}

Related

comment resolu problem sql.java.sql.SQLException

private void totaleActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement ps;
ResultSet rst;
String query="SELECT SUM( montant_m) FROM `mnd` ";
String num_m = jTF1.getText();
try {
ps=Connecteur_db.connecterDB().prepareStatement(query);
// ps.setString(1, num_m);
rst=ps.executeQuery();
if(rst.next()){
String som_t = rst.getString("SUM(montant_m)");
jLabe_resultat.setText(""+som_t);
JOptionPane.showMessageDialog(null,""+som_t);
}
} catch (SQLException ex) { java.util.logging.Logger.getLogger(noveau_j.class.getName()).log(Level.SEVERE, null, ex);
}
}
While trying to execute this i am getting an error like "Caused by: java.sql.SQLException: Column 'SUM(montant_m)' not found.
at What is the problem here?? Please help me..
Sorry for my poor english
This is myconnecteur_db() class the connection
public static Connection connecterDB() {
Connection conx = null;
String pilot = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(pilot);//chargement de driver
System.out.println("Driver ok");
String url = "jdbc:mysql://localhost:3307/tc";
String user = "root";
String pw;
pw = "root";
Connection con = DriverManager.getConnection(url, user, pw);
System.out.println("la connection est bien etablir");
return con;
} catch (Exception e) {
System.out.println("Echec connection!!");
e.printStackTrace();
return null;
}
}
I assume this is occuring at the line rst.getString("SUM(montant_m)")
SUM(montant_m) doesn't have a space before montant_m.
To make it easier, use the query:
SELECT SUM(montant_m) AS total FROM mnd
And then rst.getString("total")

Sqlserver show results in joptionpane with sql query

Hi I want to bring results from a table using SQL query but I am getting the message SQLServerResultSet3 as a result.
I take as an example the below code but it isn't working for me, any idea what I did wrong cause I am new to this ty!
searching from database and showing the output
private void searchquantity(){
//ArrayList <Update_del_insert_products> proList =new ArrayList <Update_del_insert_products> ();
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
//Update_del_insert_products update_del_insert_products ;
if(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr);
}else{
JOptionPane.showMessageDialog(null, "Not Found");
}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}
=================================================================
private void Check_CapacityActionPerformed(java.awt.event.ActionEvent evt) {
searchquantity();
}
check rows for products that are below 20 in quantity table
private void searchquantity(){
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
int a=0;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
while(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Id"));
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Name"));
a=1;
}
if (a==0){
JOptionPane.showMessageDialog(null, "Not Found");
a=0;}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}

How to auto refresh jComboBox data after update?

I have a jComboBox that getting data from MySQL server database.
When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.
How can I refresh jComboBox data automatically?
This is my code :
private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}
can you help me?
thank you..
You can do it in this way it will automatically refresh the combobox
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
removeAllItems(); method will clean the combobox to insure that not to repeat values.
You do not need to create a separate Object to add in jComboBox instead you can add String too.
Inzimam Tariq IT's Code (above):
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
I suggest putting all of this code inside an ActionListener. So that each time there the mouse is entered over the comboBox the above code will run. You should do the following:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
I suggest using a mouseListener:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But if you want to look at other ActionListeners you can see them here:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Once you add a new registry in the DB, do a removeAllItems comboBox.removeAllItems(); and repopulate de combobox,
My example:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");

Java MySQL and JFrame connection "Cannot convert from boolean to connection"

public class BancoDeDados {
static String url = "jdbc:mysql://localhost:3306/Estoque";
static String pass = "admin";
static String user = "admin";
static Connection conexao = null;
public static boolean conecta() throws ClassNotFoundException {
try {
Class.forName("mysql.Driver");
conexao = DriverManager.getConnection(url, user, pass);
//System.out.println("Conectado.");
JOptionPane.showMessageDialog(null, "Conectado com Sucesso!");
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Usuário e/ou senha estão incorretos!");
//System.out.println("Usuário e/ou senha estão errados.");
return false;
}
}
public class TelaPrincipal extends JFrame {
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
private JPanel contentPane;
private JTextField textLogin;
private JPasswordField textSenha;
public void logar(){
String sql = "Select *from Login WHERE Usuario = ? and senha = ?";
try{
pst = conexao.prepareStatement(sql);
pst.setString(1, textLogin.getText());
pst.setString(2, textSenha.getText());
rs = pst.executeQuery();
if(rs.next()){
TelaOpcoes telaopcoes = new TelaOpcoes();
telaopcoes.setVisible(true);
dispose();
}
else{
JOptionPane.showMessageDialog(null, "Usuário e Senha Inválidos");
}
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() throws ClassNotFoundException {
conexao = BancoDeDados.conecta();
this.setLocationRelativeTo(null);
Its doing error on penultimate line " CONEXAO = BANCODEDADOS.CONECTA(); " saying that "Type mismatch : cannot convert from boolean to Connection"
Can somebody help me please? thanks!
CONEXAO = BANCODEDADOS.CONECTA();
Here CONEXAO is a connection variable
but the method
BANCODEDADOS.CONECTA(); returns a boolean value.
so change the type of variable CONEXAO
or create a new variable boolean type for store the result
Boolean conexao = BancoDeDados.conecta();
Your method returns a boolean (not a Connection). Change
public static boolean conecta() throws ClassNotFoundException {
try {
Class.forName("mysql.Driver");
conexao = DriverManager.getConnection(url, user, pass);
//System.out.println("Conectado.");
JOptionPane.showMessageDialog(null, "Conectado com Sucesso!");
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Usuário e/ou senha estão incorretos!");
//System.out.println("Usuário e/ou senha estão errados.");
return false;
}
}
to something like
public static Connection conecta() {
Connection conn = null;
try {
Class.forName("mysql.Driver");
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
You are returning boolean from method conecta() and in constructor you are storing it to java.sql.Connection...
So change the return type of conecta() method to java.sql.Connection..
conexao is object of Connection and you are assigning value of method call BancoDeDados.conecta();[Which return boolean] to Connection.
Change your code like
Boolean result = BancoDeDados.conecta();
Or return conexao from method conecta to support your code.
Edit:
Driver to connect MySQL is com.mysql.jdbc.Driver. Change your code
Class.forName("mysql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");

JDBC rollback method not behaving like expected

I'm developing a software in Java processing data in a MySQL database and I'm facing an issue due to a rollback call not doing what I was expecting ... My function is composed of two queries and I need to rollback if the second query is not executed (or with errors) in order to keep consistent data. Here is my code, I've been doing a syntax error on purpose for throwing an error during the second query execution. The rollback method is called but my first statement is executed and committed in my database, can you explain me why ?
#Override
public void updateIndicatorRemainingTimeAndExecuted(int id) throws ServiceException {
PreparedStatement stmt = null;
Connection con = null;
String query1 = "UPDATE "+indicatorSchedulerTable+" i "
+"JOIN adv_frequency f ON i.id_frequency = f.id_frequency "
+"SET i.ind_remainingtime = i.ind_remainingtime + f.frq_seconds WHERE id_indicator = ?";
String query2 = "UPDATE "+indicatorSchedulerTable
+" SET ind_executing = WHERE id_indicator = ?";
try {
con = mySQLManipulator.getConnection();
stmt = con.prepareStatement(query1);
stmt.setInt(1,id);
/*Updating remaining time*/
stmt.executeUpdate();
stmt.close();
/*Updating executing status*/
stmt = con.prepareStatement(query2);
stmt.setInt(1,id);
stmt.executeUpdate();
con.commit();
} catch (SQLException e) {
try {
con.rollback();
System.out.println("ROLLBACK OK");
} catch (SQLException e1) {
throw new ServiceException("Problème de rollback lors de la mise à jour dans la fonction \"updateIndicatorRemainingTimeAndExecuted\" : "+e1.getMessage()+e.getMessage());
}
throw new ServiceException("Problème lors de la mise à jour dans la fonction \"updateIndicatorRemainingTimeAndExecuted\" : "+e.getMessage());
} finally {
handleDatabaseClosure(con, stmt, null);
}
}
I'm also using a pool of connection like this maybe the error is because of this :
public class JDBCManipulator {
private static final BasicDataSource dataSource = new BasicDataSource();
private DBType type = null;
private String URI = null;
public JDBCManipulator(DBType type, String URI, String user, String password) throws Exception {
if(type == DBType.PHOENIX){
Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
} else if(type == DBType.MYSQL) {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(URI);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMaxActive(20);
dataSource.setDefaultAutoCommit(false);
} else {
throw new Exception("Le type fournit ("+type+") pour l'initialisation de JDBCManipulator n'est pas connu ...");
}
this.type = type;
this.URI = URI;
}
public Connection getConnection() throws SQLException {
Connection conn = null;
if(type == DBType.MYSQL){
conn = dataSource.getConnection();
} else {
conn = DriverManager.getConnection(URI);
}
return conn;
}
}
You have to set autoCommit of the connection to false.
con.setAutoCommit(false);
Otherwise, each executed update would be commited immediatelly.
In addition, use a storage engine that supports transactions like InnoDB. MyISAM does not support transactions.
I was able to get everything working by replacing ENGINE=MyISAM with ENGINE=INNODB in my CREATE statement. Thank you all for your help!

Categories