im trying to get the data form this jFrame including the data from the jTable and please consider that the values of the table ( the rows number might change )
I've written this code but its not working and I'm a beginner so please if anyone can help
ive tried this code and no values are being inserted to mysql Table
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.DriverManager");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/StudentAttendence","root","Qjrq3Y3d38");
int rows=jTable1.getRowCount();
for(int row = 0; row<rows; row++)
{
String StudentID = (String)jTable1.getValueAt(row, 0);
String Student_Name = (String) jTable1.getValueAt(row, 1);
String Subject_ = (String)subject.getSelectedItem().toString();
String Date_ = (String)date.getDateFormatString();
Boolean Attendance = (boolean) jTable1.getColumnSelectionAllowed();
String query = "Insert into attendance(StudentID,Student_Name,Subject_,Date_,Attendance) values ('"+StudentID+"','"+Student_Name+"','"+Subject_+"','"+Date_+"','"+Attendance+"')";
pst = con.prepareStatement(query);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
}
Related
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";
Hello so i'm trying to code my own type of error catching on a sql statement. On my method add order i want to add some way of stopping someone from selling a product which has no stock. My code below does not yet do that. I can add orders and update the stock amount but i haven't figured out a way of adding an if statement that works.
#FXML
public void AddOrder(ActionEvent event) {
String orderID = orderBox.getText();
String customerID = customerBox.getText();
String productID = productBox.getText();
String amount = amountBox.getText();
// String cost = costBox.getText();
String date = dateBox.getText();
PreparedStatement sample;
dc = new Database();
try {
c = dc.Connect();
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
while (rs.next()) {
Integer amount2 = rs.getInt("Amount");
if (amount2 <= 0) {
System.out.println("No stock exists");
} else {
query = c.prepareStatement(
"INSERT INTO ordertable (orderID,customerID,productID,Amount,Date)VALUES(?,?,?,?,?)");
update = c.prepareStatement("UPDATE inventory set stockAmount = stockAmount-? WHERE productID =?");
update.setString(1, amount);
update.setString(2, productID);
update.execute();
query.setString(1, orderID);
query.setString(2, customerID);
query.setString(3, productID);
query.setString(4, amount);
// query.setString(5, cost);
query.setString(5, date);
query.executeUpdate();
// update.executeUpdate();
Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "Saved");
// closeConfirmation.showMessageDialog(this, "Saved");
confirmation.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
orderBox.clear();
customerBox.clear();
productBox.clear();
amountBox.clear();
dateBox.clear();
loadDataFromDatabase(event);
}
Below is the error i'm getting
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at
If you are just having trouble because of that exception, check these lines:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
The query is defined to accept a parameter for productID, but you haven't given it a value prior to executing the statement. You'll need to change the query so that it doesn't require a parameter or assign a value to the parameter, like this:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
sample.setString(1, productID);
ResultSet rs = sample.executeQuery();
I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.
I am writing a simple database with a query that inserts some data, modifies a entry, deletes it, then prints out the rest.
import java.sql.*;
public class SpotifyDB {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/spotify";
static final int portNumber = 3306;
static final String serverName = "localhost";
static final String dbName = "spotify";
//Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection to the database
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Insert data
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO artist(artist) " +
"values('Muse')";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('Drones', 'Muse', 'Rock', 2015)";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('The 2nd Law', 'Muse', 'Rock', 2012)";
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Madness', 'Muse', 'The 2nd Law', 2, '4:41')");
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Mercy', 'Muse', 'Drones', 4, '3:52')");
stmt.executeUpdate(sql);
System.out.println("Records inserted into the table!");
//Update data
String sql1 = "UPDATE songs " +
"SET track number = 1 WHERE song in ('Madness')";
stmt.executeUpdate(sql1);
//Delete data
String sql2 = "DELETE FROM songs " +
"WHERE song = Madness";
stmt.executeUpdate(sql2);
//View records
String sql3 = "SELECT * FROM songs";
ResultSet rs = stmt.executeQuery(sql3);
while(rs.next()) {
//Retrieve by column name
String song = rs.getString("song");
String artist = rs.getString("artist");
String album = rs.getString("album");
String track = rs.getString("track number");
String duration = rs.getString("duration");
//Display the values
System.out.print("Song: " + song);
System.out.print(", Artist: " + artist);
System.out.print(", Album: " + album);
System.out.println(", Track: " + track);
System.out.println(", Duration: " + duration);
}
//Close the connection, clean up running functions
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se) {
//Handle errors for JDBC driver
se.printStackTrace();
}
catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
finally {
//finally used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2) {
}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
My SQL Database table is quite simple as well;
CREATE TABLE spotify.`songs` (
`song` varchar(20) NOT NULL,
`artist` varchar(20) NOT NULL,
`album` varchar(20) NOT NULL,
`track number` int(3) NOT NULL,
`duration` varchar(10) NOT NULL,
PRIMARY KEY (`song`),
KEY `songalbum_idx` (`album`),
KEY `songartist` (`artist`),
CONSTRAINT `songalbum` FOREIGN KEY (`album`) REFERENCES `album` (`album`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `songartist` FOREIGN KEY (`artist`) REFERENCES `artist` (`artist`)
ON DELETE CASCADE
ON UPDATE CASCADE);
and the console is returning me this error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
I am having trouble seeing where the table columns are not matching up, any help would be appreciated. Thank you!
Column names really shouldn't have spaces, for exactly this reason. But if your column names must have spaces then you need to qualify them with back-ticks exactly as you do in your CREATE TABLE statement:
INSERT INTO songs (song, artist, album, `track number`, duration) VALUES ...
Otherwise after the identifier track the query engine is expecting either a comma (to move on to another identifier) or a close parentheses (to end the list of column identifiers). It finds neither of this, and immediately finds another identifier (number, which may even be a reserved word?). This confuses the query parser.
I have a method that returns an array list of search results from my database.
Instead of:
Select *
from employee
where first_name like ?
I would rather use:
Select *
from employee
where ? like ?
but I'm not sure if this is even possible? there's no errors when I compile it in eclipse but it keeps giving me blank values in the array. Is there something I'm doing wrong?
This is the method that gives me the blank value it works fine when I have where first_name like ? so I know the logic works.
public static ArrayList<String> AdvanceSearchFirstName(String selected, String searchTerm) {
String selectQuery = "select * from employee_info where ? like ?";
ArrayList<String> searchResults = new ArrayList<>();
try {
stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement(selectQuery);
ps.setString(1, selected);
ps.setString(2, '%'+searchTerm+'%');
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String studentNumber = rs.getString("employee_number");
String combo = employeeNumber + " " + firstName + " " + lastName;
searchResults.add(combo);
}
} catch (SQLException e) {
e.printStackTrace();
}
return searchResults;
}
I've looked over a lot of posts so I'm pretty sure this hasn't been posted but I apologies if this is a double. I'm new to programming and sql so any help is appreciated.