When i try to get an element by a few arguments in my Servlet, its values returns NULL. What can I do?
Class DAO:
public Premio getByDataLoteriaHorario(String date, int idLoteria, int idHorario) throws SQLException, ClassNotFoundException, ParseException {
Connection connection = ConnectionFactory.getConnection();
ResultSet rs;
Premio premio = new Premio();
String sqlString = "select * from Premio where dataPremio = ? AND idLoteria = ? AND idHorario = ?";
DateFormat df = new SimpleDateFormat("YYYY/MM/DD");
java.sql.Date data = new java.sql.Date(df.parse(date).getTime());
PreparedStatement preparedStatement = (PreparedStatement) connection.prepareStatement(sqlString);
preparedStatement.setDate(1, data);
preparedStatement.setInt(2, idLoteria);
preparedStatement.setInt(3, idHorario);
rs = preparedStatement.executeQuery();
while(rs.next()) {
premio.setIdPremio(rs.getInt("idPremio"));
premio.setIdLoteria(rs.getInt("idLoteria"));
premio.setIdHorario(rs.getInt("idHorario"));
premio.setIdGrupo(rs.getInt("idGrupo"));
premio.setPremio(rs.getString("premio"));
premio.setDataPremio(rs.getString("dataPremio"));
}
preparedStatement.close();
rs.close();
return premio;
}
The MySQL Table:
CREATE TABLE Premio (
idPremio INT NOT NULL AUTO_INCREMENT,
idLoteria INT,
idHorario INT,
idGrupo INT,
premio1 VARCHAR(4),
premio2 VARCHAR(4),
premio3 VARCHAR(4),
premio4 VARCHAR(4),
premio5 VARCHAR(4),
premioSoma VARCHAR(5),
premio7 VARCHAR(4),
dataPremio DATE,
FOREIGN KEY (idLoteria) REFERENCES Loteria(idLoteria),
FOREIGN KEY (idHorario) REFERENCES Horario(idHorario),
FOREIGN KEY (idGrupo) REFERENCES Bicho(idGrupo),
PRIMARY KEY (idPremio)
);
I think the error is when you call the database to award and dataPremio you send them in the rs.getString but I do not see them in your table I remain attentive to an answer
I change all the Date types to String and it works! ¯\_(ツ)_/¯
Related
saveProfit method
public void saveProfit() throws SQLException {
ObservableList<Bread> bread = FXCollections.observableArrayList();
Connection conn = null;
PreparedStatement ps = null;
Statement statement = null;
ResultSet resultSet = null;
try {
conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/bakery", "root", "a3756421");
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT * FROM bread");
while (resultSet.next()) {
Bread newBread = new Bread(
resultSet.getString("breadName"),
resultSet.getString("breadType"),
resultSet.getString("breadFlavour"),
resultSet.getInt("breadStock"),
resultSet.getInt("breadPrice"));
newBread.setBreadId(resultSet.getInt("breadId"));
bread.add(newBread);
}
for(Bread b : bread){
String sql = "insert into best5(pname, profit) values (?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,b.getBreadName());
ps.setInt(2, b.getBreadPrice()*b.getBreadStock());
}
for(Bread b : bread){
String sql = "insert into worst5(pname, profit) values (?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,b.getBreadName());
ps.setInt(2, b.getBreadPrice()*b.getBreadStock());
}
}
}
Bread object
public class Bread {
private String breadName, breadFlavour, breadType;
private int breadStock, breadPrice, breadId;
private File imageFile;
private Image photo;
public Bread(String breadName, String breadType, String breadFlavour,int breadPrice, int breadStock) {
setBreadName(breadName);
setBreadType(breadType);
setBreadFlavour(breadFlavour);
setBreadPrice(breadPrice);
setBreadStock(breadStock);
setImageFile(new File("./src/Images/foodDefault.png"));
}
bread table
create table bread (
breadId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
breadName VARCHAR(30),
breadType VARCHAR(30),
breadFlavour VARCHAR(30),
breadStock INT,
breadPrice DOUBLE,
imageFile VARCHAR(100));
best5 table
create table best5 (
id INT not null primary key auto_increment,
pname VARCHAR(30),
profit INT);
worst5 table is basically the same with different name.
So, I am trying to loop the insert into best5(pname, profit) values(?,?) to store data from bread table. But, it seems like only the first row of bread table is stored into best5 table and the rest is ignored. What am I doing wrong? I am new to javafx and MySQL. Please correct my mistakes.
Trying to create CRUD application using jdbc and mysql. I have Person.class and two tables in Database:
class Person {
String name;
String surname;
List<String> phones;
}
Tables:
`phone`
(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`owner` INT UNSIGNED NOT NULL,
`number` VARCHAR(50) NOT NULL,
CONSTRAINT `PK_phone` PRIMARY KEY (`id`)
)
`person`
(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`surname` VARCHAR(150) NOT NULL,
`name` VARCHAR(150) NOT NULL,
CONSTRAINT `PK_phonebook` PRIMARY KEY (`id`)
)
ALTER TABLE `phone`
ADD CONSTRAINT `FK_phone_person`
FOREIGN KEY (`owner`) REFERENCES `person` (`id`) ON DELETE Cascade ON UPDATE Cascade
;
SET FOREIGN_KEY_CHECKS=1 ;
How i can add person with field List phones to database using Servlets???
For example: Harry Smith +37521987902
+56727172713
+45679012214
The idea is simple, you can use this way
Insert your person
get the id of that person
insert the list of phone
You can use it like this :
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(DB_URL, DB_username, DB_password);
String query = "INSERT INTO person (surname, name) values(?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "hello");
preparedStatement.setString(2, "jdbc");
int affectedRows = preparedStatement.executeUpdate();
long id = 0;
if (affectedRows > 0) {
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
id = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement("INSERT INTO phone (owner, number) values(?, ?)");
for (String phone : listePhone) {
preparedStatement.setLong(1, id);
preparedStatement.setString(2, phone);
ps.addBatch();
}
ps.executeBatch();
connection.commit();
}
You can learn how to execute multiple statement in one shot, using statement-batching
I'm trying to do an update on a ResultSet and I'm getting an exception, No primary key found for table nvp, on a table that has a primary key.
It's PostgreSQL 9.6.1.0, and jdbc driver version is postgresql-9.4.1212.jar downloaded from their website (JDBC42 Postgresql Driver, Version 9.4.1212 from here).
#Test
public void testUpdateableResultSet() throws Exception {
String url = "jdbc:postgresql://localhost:5432/dot";
Properties props = new Properties();
props.setProperty("user", "dot_test");
props.setProperty("password", "test_dot");
props.setProperty("currentSchema", "dot_test");
try(Connection conn = DriverManager.getConnection(url, props)) {
conn.setAutoCommit(false);
try(Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
s.execute("drop table if exists nvp");
s.execute("create table nvp (id int primary key, value text);");
s.execute("insert into nvp (id, value) values (1, 'one_'), (2, 'two_')");
}
try(PreparedStatement ps = conn.prepareStatement("select value from nvp",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
String s = rs.getString(1);
if(s.endsWith("_")) {
s = s.replace("_", "");
}
else {
s = s + "_";
}
rs.updateString(1, s); // line 28
System.out.println("row updated");
}
}
}
}
With the following result.
Testcase: testUpdateableResultSet(com.tekbot.lib.sql.SimpleTest): Caused an ERROR
No primary key found for table nvp.
org.postgresql.util.PSQLException: No primary key found for table nvp.
at org.postgresql.jdbc.PgResultSet.isUpdateable(PgResultSet.java:1586)
at org.postgresql.jdbc.PgResultSet.checkUpdateable(PgResultSet.java:2722)
at org.postgresql.jdbc.PgResultSet.updateValue(PgResultSet.java:3056)
at org.postgresql.jdbc.PgResultSet.updateString(PgResultSet.java:1393)
at com.tekbot.lib.sql.SimpleTest.testUpdateableResultSet(SimpleTest.java:28)
Is this a bug? Am I missing a step?
The primary key must be specified so that the result set is updateable
Change your query on line 17 to:
PreparedStatement ps = conn.prepareStatement("select id, value from nvp"...
I have a DB schema that creates several tables and fills them with data. I want to check whether db contains corresponding tables or not during app start. I could check for db file existence, but H2 creates db if it doesn't exist. So the only way, I think, is to check for tables existence.
Here is the code of how I initialize DB:
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS table1 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS table2 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS daily_record_stat (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, date DATE, table1_id INT, table1_record INT, table2_id INT," +
" table2_record INT, total_record INT);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table1_id) REFERENCES table1(id);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table2_id) REFERENCES table2(id);");
st.execute("INSERT INTO table1 VALUES(1, 'non_existed_stub', 0, NULL)");
st.execute("INSERT INTO table2 VALUES(1, 'non_existed_stub', 0, NULL)");
conn.close();
As you see, I check for table existence before creation using IF NOT EXISTS statement. But then I run at the problem with ALTER and INSERT - these commands don's allow IF usage.
I tried to do the following:
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
ResultSet meta = conn.getMetaData().getTables(null, null, "table1", null);
if(meta.next()) {
//do something
}
But meta.next() is false.
So how to check whether table schema is initialized? Or maybe this should be done some other way?
Not sure if that's what you mean by saying to check programmatically, buy you can try to use DatabaseMetaData.getTables(). This call will return ResultSet which you'll have to check programmatically. You can see what fields are returned in this ResultSet in corresponding section here. And meta data itself can be obtained by conn.getMetaData().
Following code should return all tables which names start with 'TABLE':
ResultSet meta = conn.getMetaData().getTables(null, null, "TABLE%", new String[]{"TABLE"});
while (meta.next()) {
System.out.println(meta.getString(3));
}
Note that you have to specify table name pattern in upper case. Also it's good to pass table types that you need, although it is optional.
This is a check I used to (re)create the H2 database:
// IMPORTANT A sorted list of table names.
private static final String[] REQUIRED_TABLES = { "USER", ... };
public static final String CREATE_USER = "create table USER (...)";
private boolean schemaExists() throws SQLException {
final List<String> requiredTables = Arrays.asList(REQUIRED_TABLES);
final List<String> tableNames = new ArrayList<String>();
final Connection conn = dataSource.getConnection();
try {
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
rs.close();
st.close();
}
finally {
if (conn != null) { conn.close(); }
}
Collections.sort(tableNames);
return tableNames.equals(requiredTables);
}
private void initializeDatabase() throws SQLException {
final Connection conn = dataSource.getConnection();
try {
if (schemaExists()) {
return;
}
final Statement st = conn.createStatement();
st.executeUpdate(CREATE_USER);
conn.commit();
}
finally {
if (conn != null) { conn.close(); }
}
}
And you just call:
initializeDatabase();
Notice the list of required tables has to be sorted because I use List.equals() to compare two lists. It would probably be better to also programmatically sort the required tables list too.
It's not fool-proof (not checking if any table exists and if it should be altered) but it works for me.
Take a look at the SHOW command for other uses.
Table
id int(11) No auto_increment Change Drop Primary Index Unique Fulltext
email varchar(45) latin1_swedish_ci No Change Drop Primary Index Unique Fulltext
billpayment tinyint(1) No Change Drop Primary Index Unique Fulltext
dispatch tinyint(1) No Change Drop Primary Index Unique Fulltext
address varchar(75) latin1_swedish_ci Yes NULL Change Drop Primary Index Unique Fulltext
phone int(11) Yes NULL Change Drop Primary Index Unique Fulltext
created_at datetime No Change Drop Primary Index Unique Fulltext
totalbillamount float Yes NULL Change Drop Primary Index Unique Fulltext
Java Code:
sql = "insert into session_shopping (email,billpayment,dispatch,address,phone,created_at,totalbillamount) values(?,?,?,?,?,?,?)";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, email);
ps.setBoolean(2, false);
ps.setBoolean(3, false);
ps.setString(4, "");
ps.setInt(5, 0);
java.util.Date date = new java.util.Date();
long t = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(t);
ps.setDate(6, sqlDate);
ps.setFloat(7, 00.0f);
int newId = ps.executeUpdate();
System.out.println("newId" + newId);
if (newId == 1) {
sql = "select * from session_shopping where id = ?";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, newId);
ResultSet reS = ps.executeQuery();
Session s = new Session();
s.setId(reS.getInt("id"));
s.setEmail(reS.getString("email"));
System.out.println("retreived");
return s;
} else {
System.out.println("unable to save");
}
This code fails because int newId is boolean
What i want to do is. I want to retrieve the row which i added just now.
executeUpdate will return the number of rows affected, not the current row .
Try this
ResultSet rs = aStatement.executeQuery("SELECT LAST_INSERT_ID()");
while(rs.next())
{
key = rs.getInt(1);
}
The value returned by executeUpdate has nothing to do with your ID.
Before we go to getting your ID, you can start off by setting email in the Session from your email variable rather than pulling it back out of the database.
As things stand, the only way I can think of to get the newly inserted ID is by changing your SQL thus:
sql = "select max(id) from session_shopping";
This will give you problems if you get another insert before you pick out the maximum ID though. To prevent that, put the select in the same transaction as your insert.