Insert values in existing record. sqlite using prepared statement - mysql

I want to insert values into an existing record using prepared statment. The value of that record is the last record inserted, I tried LAST function and MAX but it didn't seems to work, also I tried SELECT statment inside INSERT with no luck.
public static void insertCoordinates(){
java.sql.Connection c = null;
try {
String str1 = Singelton.getInstance().getTxtField1().getText();
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:timeline_DB.db");
c.setAutoCommit(false);
PreparedStatement preparedStatement = c.prepareStatement("insert into event_table(bar_length, x_bar, y_bar) values (?, ?, ?) WHERE event_title =?");
preparedStatement.setInt(1, CanvasNewTimeLine.Event_length);
preparedStatement.setInt(2, CanvasNewTimeLine.x);
preparedStatement.setInt(3, CanvasNewTimeLine.H_LINE);
preparedStatement.setString(4,str1);
preparedStatement.executeUpdate();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
System.err.println("problem");
}
System.out.println("yesssssss successfully");
}

I used update instead of insert:
public static void insertCoordinates(){
java.sql.Connection c = null;
try {
String str1 = Singelton.getInstance().getTxtField1().getText();
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:timeline_DB.db");
c.setAutoCommit(false);
String updateTableSQL = "UPDATE event_table SET bar_length = ?, x_bar=?, y_bar=? WHERE event_title = ?";
PreparedStatement preparedStatement = c.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, CanvasNewTimeLine.Event_length);
preparedStatement.setInt(2, CanvasNewTimeLine.x);
preparedStatement.setInt(3, CanvasNewTimeLine.H_LINE);
preparedStatement.setString(4,str1);
// execute
preparedStatement .executeUpdate();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
System.err.println("problem");
}
System.out.println("yesssssss successfully");
}

Related

" check if Table is exist or not in database " is not working

I am trying to make a java program can call a table by its name... but the problem is I couldnt figure out how to check if the table is exist or not in database... I am using phpmyadmin data base and here is my code if there is someone can help me ...
enter image description here
public boolean istableNameexist(String un){
boolean uexist = false;
Connection con = myConnection.getconnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = con.prepareStatement("SELECT * FROM `javacontactapp` WHERE TABLE_NAME = ?");
ps.setString(1,name.getText());
rs = ps.executeQuery();
if (rs.next()){
uexist = true;
}
} catch (Exception e) {
System.out.println("wrong");
}
return uexist;
}
public void openfatura(ActionEvent actionEvent) {
String ff1 = name.getText();
Connection con = myConnection.getconnection();
if (!name.getText().isEmpty()) {
if (istableNameexist(name.getText())){
try {
PreparedStatement ps = con.prepareStatement("SELECT `dafat`, `sinif` ,`number` , `price`, `type`, `total` FROM " + ff1 + " WHERE `id` = 1");
ResultSet resultset = ps.executeQuery();

"JSP First Connection cause second connection not running when it had ended"

I'm trying to get two data(GenreID & GameID) from two different tables(genre & games) and insert them into another table(games_genre). However, it will close the connection to the database after inserting the GenreID successfully even though i had created another new connection to the database.
I have tried to create connection1 and connection2 to the same database. Connection1 is used to insert GenreID and connection2 is used to insert GameID
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
Connection conn2 = DriverManager.getConnection(connURL);
Statement stmt = conn.createStatement();
if (checkbox1!= null){
for(String s: checkbox1){
String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";
ResultSet rs = stmt.executeQuery(sqlStr2);
while(rs.next()){
String genreid = rs.getString("GenreID");
String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
int j = stmt.executeUpdate(sqlStr3);
if (j>0) {
out.println("Adding GenreID Successfully!");}
}
}
}
conn.close();
Statement stmt2 = conn2.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
String gameid = rs2.getString("GameID");
String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
int k = stmt2.executeUpdate(sqlStr5);
if (k>0) {
out.println("Adding GameID Successfully!");
}
}
conn2.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Adding Game Successfully! Adding GenreID Successfully! Error :java.sql.SQLException: Operation not allowed after ResultSet closed
I don't understand that why do you need to create two Connection as you need to access same database . So ,just create multiple Statement to execute multiple query like below :
Statement stmt=null;
Statement stmt2=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
stmt = conn.createStatement();
if (checkbox1!= null){
....
}
<!--using same conn object -->
stmt2 = conn.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
...
}
<!--finally close connection-->
conn.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Note : Also try using PreparedStatement for preventing from Sql Injection as concatenating values into a query string is unsafe .

Does MySQL support's creation of hidden column? [duplicate]

I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";

I want to count a column in mysql and place the results in a textfield

I have a mysql data base with a column called MemType this column will have whether a member is active. Not all members are active. I want to count the active members and display the result in a textField. I can do the count but don't know how the result comes back. My code folows:
#FXML
private void CountActionPerformed(ActionEvent event) {
String user = "root";
String password = "";
String ResultSet = null; // This is to ensure that ResultSet is empty.
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/club", user, password);
System.out.println("Connection Successful ");
// Create statement.
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(MemType)\n "
+ "FROM members \n "
+ "WHERE MemType = 'Active ' ");
while (myRs.next()) {
CountRel.setText(myRs.getString("MemType"));
}
} catch (Exception e) {
}
}
You can give the column an alias like this:
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(MemType) as MemType "
+ "FROM members "
+ "WHERE MemType = 'Active ' ");
This should be all the changes you need and you will have only one result (The count of all the Active rows)
The result is a table with a single column and a single row. You can retrieve the result using the column index:
try {
try (Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/club", user, password)) {
System.out.println("Connection Successful ");
// Create statement.
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(*) "
+ "FROM members "
+ "WHERE MemType = 'Active '");
if (myRs.next()) {
CountRel.setText(Integer.toString(myRs.getInt(1)));
} else {
throw new Exception("error while counting");
}
}
} catch (Exception e) {
}

ArrayIndexOutOfBoundsException ExecuteBatch() on PreparedStatement

I'm adding 483 objects to a database with preparedStatements and ExecuteBatch().
When I run this code, all the objects are correctly added to the database but after a while the program throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 484
at com.mysql.jdbc.StatementImpl.processMultiCountsAndKeys(StatementImpl.java:1417)
at com.mysql.jdbc.PreparedStatement.executePreparedBatchAsMultiStatement(PreparedStatement.java:1515)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1389)
at model.database.SQLCommand.insertMeasurements(SQLCommand.java:110)
at model.database.SQLCommand.addDatasetToDb(SQLCommand.java:31)
at tests.readText.main(readText.java:35)
Here is my code:
private static List<Long> insertMeasurements(List<Measurement> measurements, long did) throws SQLException {
conn.setAutoCommit(false);
List<Long> mids = new ArrayList<Long>();
String sql = "INSERT INTO doses (CPS, ground, total) VALUES (?, ?, ?);" + " " +
"INSERT INTO places (x, y, z, speed) VALUES (?, ?, ?, ?);" + " " +
"INSERT INTO measurements (time, place, note, dose, id_dataset) VALUES (?, (SELECT MAX(ID) FROM places), ?, (SELECT MAX(ID) FROM doses), ?)";
try (
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
for(Measurement measurement: measurements) {
ps.clearParameters();
double cps = measurement.getDose().getCps();
double ground = measurement.getDose().getGround();
double total = measurement.getDose().getTotal();
ps.setDouble(1, cps);
ps.setDouble(2, ground);
ps.setDouble(3, total);
double x = measurement.getPlace().getX();
double y = measurement.getPlace().getY();
double z = measurement.getPlace().getZ();
double speed = measurement.getPlace().getSpeed();
ps.setDouble(4, x);
ps.setDouble(5, y);
ps.setDouble(6, z);
ps.setDouble(7, speed);
String time = measurement.getDate().toString();
String note = measurement.getNote().toString();
ps.setString(8, time);
ps.setString(9, note);
ps.setObject(10, did);
ps.addBatch();
}
ps.executeBatch();
conn.commit();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
long id = rs.getLong(1);
mids.add(id);
}
} catch (SQLException e) {
throw new SQLException("Can't add the measurement."+e.toString()+"\n" );
}
return mids;
}