MySQL looping "insert into" - java

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.

Related

How do I add the auto increment values with java?

I created a table in Mysql using
Create table
(
id int auto_increment,
us varchar(100),
ps varchar(1000)
);
And used java for adding values thru my GUI application:
I used the following method to add values into my database:
public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String hashpass=passhash(p);//throws declaration for this statement
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (id,us,ps)"
+ " values (?,?, ?)";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
int id=0;
while(rs.next())
{
id= rs.getInt(1);
}
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, id++); //I don't want this method because id is auto increment
preparedStmt.setString(2,u);
preparedStmt.setString(3,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){ System.out.println(e);}
}
Everything works fine
But the id is the auto_increment and I don't need to add value to id while adding other column values.
I can't add like that while adding thru java like only adding us, ps columns and the id will be automatically incremented.
Are there any methods to add data without passing the parameters?
Remove the column id from the sql statement:
String query = "insert into login (us, ps) values (?, ?)";
and don't set any value for it in the prepared statement, so remove this line:
preparedStmt.setInt(1, id++);
The column id is auto_inrement so its value will be set by MySql.
Of course change the indices of the other lines to 1 and 2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
You might insert data without ID as it will be auto-generated from SQL
public static void Mysql(String u,String p) throws NoSuchAlgorithmException, InvalidKeySpecException {
String hashpass=passhash(p);
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (us,ps) values (?, ?)"; // CHECK HERE
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){
System.out.println(e);}
}
}

Class DAO don't get the Object

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! ¯\_(ツ)_/¯

Prepared statement execute query error (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();

PostgreSQL error updating ResultSet "No primary key found for table" on table w/key

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"...

How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

Categories

Resources