I have a database file SQL
that I want to access from a Java class that makes the connection to DriverManager
and JDBC
, but I'm a bit lost.
the file is called items.sql
DBItem.java
package beans;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author elcer
*/
public class DBItem {
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/items";
private Connection conn = null;
public DBItem() { //el constructor crea y abre la conexion
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "usuario", "password");
if (conn != null)
System.out.println("Conexion efectuada con exito");
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger
(DBItem.class.getName()).log(Level.SEVERE, null, ex);
}
}
public LinkedList<Item> getItems(String tipo) {
LinkedList<Item> itemsTipo = new LinkedList<>();
if (conn != null) {
try (Statement st = conn.createStatement()) {
String sqls = "SELECT * from items WHERE tipo='" + tipo + "'";
try (ResultSet rs = st.executeQuery(sqls)) {
while (rs.next()) {
String nombre = rs.getString("nombre");
Item item = new Item(nombre, tipo);
itemTipo.add(item);
}
}
} catch (SQLException ex) {
Logger.getLogger(DBItem.class.getName()).log(Level.SEVERE, null, ex);
}
}
return itemsTipo;
}
public void closeDB() {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBItem.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I try to access the database, but it does not recognize me, it tells me that it can not be initialized and such ... Can someone help me?