I am tring to check whether a data is available or not in database table.if not it will insert the data. But in first button click it works perfectly. by when i try to click the button again with the same value it gets inserted into the table. please help someone
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
ArrayList<String> list = new ArrayList<>();
Object obj[] = null;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cem?useSSL=false", "root", "123");
//here stu is database name, root is username and password
Statement stmt = con.createStatement();
String pn = "select gname from games where gname='" + jTextField1.getText() + "'";
ResultSet rsPn = stmt.executeQuery(pn);
System.out.println(rsPn.next());
if (rsPn.next() == false) {
String q = ("insert into games(gid,gname) values(NULL,'" + jTextField1.getText() + "')");
int i = 0;
i = stmt.executeUpdate(q);
if (i > 0) {
System.out.println("success");
list.add(jTextField1.getText());
obj = list.toArray();
model.addRow(obj);
} else {
System.out.println("stuck somewhere");
}
StudentDetails.details();
jTextField1.setForeground(Color.BLACK);
stmt.close();
con.close();
} else {
jTextField1.setForeground(Color.red);
System.out.println("Name Already exist");
}
} catch (SQLException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
You're calling next() twice:
System.out.println(rsPn.next());
if (rsPn.next() == false) {
The second call will return false even if there's a row already (though it should work once there are two or more rows). Use a variable instead:
boolean hasNext = rdPn.next();
System.out.println(hasNext);
if (!hasNext) {
Related
I have it set up where I can save my object information to a SQL database using this block of code:
public boolean add(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if (aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
sqlStr.append("INSERT INTO ");
sqlStr.append(ORDER_TABLE);
sqlStr.append(" (firstName, lastName, size, cheese, sausage, ham, total)");
sqlStr.append(" VALUES (?,?,?,?,?,?,?)");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
if (rowCount == 1) {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()) {
aOrder.setId(rs.getInt(1));
}
success = true;
}
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot save pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Insert", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
What I am trying to do is change the total variable with an update to the object on the server. I dont have an error right now popping up but nothing is changing in my objects information. Here is my code with the update block:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
//TODO create the SQL and prepared statements to update an order in the database
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET firstName = ?, lastName = ?, size = ?, cheese = ?, sausage = ?, ham = ?, total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I have it set up that just the total variable will be changed by the time the update block of code will be ran. So I was trying to just call all the variables again in the hopes that it would change the total.
I get the same results with this update block of code:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I figured out my problem I had something elsewhere in my code blocking the update. This is the code that is working to update the mySQL database in this case:
try {
//TODO create the SQL and prepared statements to update an order in the database
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ?");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
statement.setInt(2, aOrder.getId());
rowCount = statement.executeUpdate();
}
I'm trying to send an increase count variable of a picture (which is increased by just increasing +1 everytime a new session hits a picture). I'm getting the following error message however, i'm checking for an empty result set. My thought process is that I can try to select the picturesNo that has been called and if it can't find that pictureNo we simply insert the first count to the table, and if it can find it, we then update this.
Error message:
"SQLException: Illegal operation on empty result set."
Code to increase the count for the session
HttpSession session = request.getSession() ;
Integer counter = (Integer) session.getAttribute("counter");
String accCount = (String) session.getAttribute("attributeKey") ;
String url = "http://localhost:8080/techfore";
String encodedURL = url + ";jsessionid=" + request.getSession().getId();
if (accCount == null || encodedURL == null) { // New session?
response.sendRedirect("/techfore/WelcomePage");
}
else{
if(counter == 0) {
counter = new Integer(counter.intValue() + 1);
session.setAttribute("counter", counter);
}
}
Utilities.initalCount(out, pictureName, counter);
Code to run the queries
public static void initalCount(PrintWriter out, String pictureName, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
}
try {
Statement stmt = con.createStatement();
String query0;
ResultSet rs1;
query0="SELECT PictureNo FROM Statistics WHERE PictureNo = (SELECT PictureNo FROM Pictures WHERE ShortName = '"+pictureName+"')";
rs1 = stmt.executeQuery(query0);
if(rs1.next()){
//yes exist
String description = rs1.getString("Description");
int pictureNo = rs1.getInt("PictureNo");
IncreaseCount(out, pictureNo, accessCount);
}
else {
//if rs is null insert
int pictureNo = rs1.getInt("PictureNo");
AddCount(out, pictureNo, accessCount);
}
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void AddCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="INSERT INTO Statistics VALUES "+pictureNo+","+accessCount+" ";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void IncreaseCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="UPDATE Statistics SET AccessCount = "+accessCount+" + 1 WHERE PictureNo = "+pictureNo+"";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
New insert
query="INSERT INTO Statistics VALUES (SELECT PictureNo FROM Pictures WHERE FileName = '"+pictureName+"'),"+accessCount+" ";
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";
What I am trying to do is get the values from a column in my SQL table, specifically a column named SubjectName. Once I have these values I want to create JButtons named for each value in the ResultSet. My current code connects to my database and as far as I can tell the query to the table also works, however when I attempt to generate and add these buttons to my display the try/catch only returns that my statement failed. The code causing the problem lies somewhere here:
try
(
Statement initializeDisplay = connect.createStatement()
){
ArrayList<String> buttonList = new ArrayList<String>();
try
{
ResultSet rs = initializeDisplay.executeQuery("SELECT SubjectName from subjectpacktable order by SubjectID");
buttonList = new ArrayList<String>();
while(rs.next())
{
buttonList.add(rs.getString(1));
}
ArrayList<JButton> listOfButtons = new ArrayList<JButton>();
for (int i=0; i < 10; i++)
{
String temp2 = rs.getString(l);
JButton button1 = new JButton(temp2);
listOfButtons.add(button1);
l++;
}
l = 0;
while(listOfButtons.get(l) != null)
{
JButton tempButton = listOfButtons.get(l);
AddCardPanel1.add(tempButton);
l++;
}
while(buttonList.get(l) != null)
{
System.out.println(buttonList.get(l));
l++;
}
l = 0;
}
catch(SQLException e1)
{
System.err.println("Initial Display Failed");
}} catch (SQLException e2)
{
System.err.println("Initial Display Failed");
}
I'm wondering if the problem lies in actually retrieving the values from the table or somewhere else in the code are values not being assigned properly. Any help is appreciated.
Instead of the while loop, do
for(int i=0;i<buttonList.size();i++)
{
System.out.println(listOfButtons.get(i).getText());
}
this should keep your index inside the array bounds
Thanks for the help everyone! I used #Dalton and #BartHofma's reccommendations and got the code up and running.
Here is the working code:
try
(
Statement initializeDisplay = connect.createStatement();
)
{
try
{
ResultSet rs = initializeDisplay.executeQuery("SELECT SubjectName from subjectpacktable order by SubjectID");
ArrayList<JButton> listOfButtons = new ArrayList<JButton>();
while(rs.next())
{
String temp2 = rs.getString("SubjectName");
JButton button1 = new JButton(temp2);
listOfButtons.add(button1);
l++;
}
for(int i=0;i<listOfButtons.size();i++)
{
JButton holderButton = listOfButtons.get(i);
final String SubjectString = listOfButtons.get(i).getText();
holderButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e1)
{
System.err.println("Connection Failed");
}
System.out.println("Driver Connected");
Connection connect = null;
try
{
connect = DriverManager.getConnection
("jdbc:mysql://localhost:3306/example","root","root1229");
}
catch (SQLException e1)
{
System.err.println("Connection Failed");
}
System.out.println("Database Connected");
String addCardStatement;
k++;
int cardID = 0;
cardID += k;
String cardFront;
String cardBack;
cardFront = JOptionPane.showInputDialog("What would you like to name the card?");
cardBack = JOptionPane.showInputDialog("What would you like to define the card as?");
addCardStatement = "INSERT INTO " + SubjectString + "VALUES (" + cardID + "," + SubjectString + "," + cardFront + "," + cardBack + ")";
try
{
Statement addStatement = connect.createStatement();
addStatement.executeUpdate(addCardStatement);
}
catch (SQLException e1)
{
System.err.println("Statement failed");
}
}});
AddCardPanel1.add(holderButton);
}
}
catch(SQLException e1)
{
System.err.println("Initial Display Failed");
e1.printStackTrace();
}} catch (SQLException e2)
{
System.err.println("Initial Display Failed");
e2.printStackTrace();
}
I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;