SQLIntegrityConstraintViolationException, - java

Im trying to create a basic program where i can add and delete data within Java Derby database. However the problem is that it throws an exception with 'The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL160724181654400' defined on 'CONTACTS_LIST'. ' The main objective is to add strings of text within 2 JTextFields and import that into my database which has only 2 colums. I do not understand where the problem is though.
try {
String writeString = "INSERT INTO Contacts_List(NAME, NUMBER) VALUES(?,?)";
PreparedStatement pst = connection.prepareStatement(writeString);
pst.setString(1, nameF.getText());
pst.setString(2, numberL.getText());
pst.execute();
showMessageDialog(this, " Contact's added! ");
nameF.setText(" ");
numberF.setText(" ");
pst.close();
} catch (Exception ex) {
ex.printStackTrace();
}
and my full code is below;
package address_book;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.showMessageDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.apache.derby.drda.NetworkServerControl;
public class Add_Data extends JFrame implements ActionListener {
JButton add = new JButton("Add To database");
JTextField nameF = new JTextField(12);
JTextField numberF = new JTextField(12);
JLabel nameL = new JLabel("Enter Name : ");
JLabel numberL = new JLabel("Enter Number : ");
private static Connection connection;
private static Statement stmt;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Add_Data().setVisible(true);
}
});
}
public Add_Data() {
super("Add Contact");
setSize(300, 250);
setVisible(true);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// add jpanel and the layout
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
// add componenets
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(nameL, constraints);
constraints.gridx = 1;
panel.add(nameF, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(numberL, constraints);
constraints.gridx = 1;
panel.add(numberF, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.CENTER;
panel.add(add, constraints);
add.addActionListener(this);
//create border
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Enter Contact's Details"));
add(panel);
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("Contacts_List").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void actionPerformed(ActionEvent e) {
String key = nameF.getText();
String name = Database.getName(key);
String nameAdd = nameF.getText();
if (nameF.getText().isEmpty() || numberF.getText().isEmpty() && e.getSource() == add) {
JOptionPane.showMessageDialog(this, "Fill the empty fields");
} else if (e.getSource() == add) {
if (name == null) {
int confirm = JOptionPane.showConfirmDialog(null, "You are about to add " + nameAdd + ", Do you want to Continue?");
if (confirm == JOptionPane.YES_OPTION) {
try {
String writeString = "INSERT INTO Contacts_List(NAME, NUMBER) VALUES(?,?)";
PreparedStatement pst = connection.prepareStatement(writeString);
pst.setString(1, nameF.getText());
pst.setString(2, numberL.getText());
pst.execute();
showMessageDialog(this, " Contact's added! ");
nameF.setText(" ");
numberF.setText(" ");
pst.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if (confirm == JOptionPane.NO_OPTION) {
showMessageDialog(this, "Please Try Again !");
}
}
}
}
}
}

Related

How do i write to a database by taking user input from a GUI and storing that user input into a database in java?

I've recently been trying to write to a Database by taking user input from a GUI and I would like to store that user input from the GUI in a derby database on netbeans. At the moment, I have got some code but it does not seem to be functional as when i run the GUI and start inputting the data that is supposed to be stored in the back end of my program in the database, it does not store that data which is being inputted in the GUI. It does not load any data onto the database!
Here is the code for writing to the Database:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* #author Hammad
*/
public class WritePlayerDB
{
private final DBConnection dbc;
private final Connection conn;
private Statement stmt;
String insertQuery;
public WritePlayerDB()
{
dbc = new DBConnection();
conn = dbc.getConnection();
}
public void writeToPlayerDB()
{
try {
int playerID = 0;
insertQuery = "INSERT INTO 'PLAYERINFO' ('PLAYER_ID', 'PLAYER_NAME', 'PRIZE_WON', 'CORRECT_ANSWERS')" + "VALUES(1,2,3,4)";
this.stmt = conn.createStatement();
this.checkExistedTable("PLAYERS");
PreparedStatement ps = conn.prepareStatement(insertQuery);
CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter] = PrizeMoney.prizeLadder[MillionaireGui.moneyCounter];
ps.setInt(1, playerID++);
ps.setString(2, MillionaireGui.nameField.getText());
ps.setInt(3, PrizeMoney.prizeLadder[MillionaireGui.moneyCounter]);
ps.setInt(4, CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter]);
ps.executeUpdate();
ps.close();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
}
public void checkExistedTable(String name)
{
try {
DatabaseMetaData dbmd = this.conn.getMetaData();
String[] types = {"TABLE"};
stmt = this.conn.createStatement();
ResultSet rs = dbmd.getTables(null, null, null, types);
while (rs.next()) {
String table_name = rs.getString("TABLE_NAME");
System.out.println(table_name);
if (table_name.equalsIgnoreCase(name)) {
stmt.executeUpdate("Drop table " + name);
System.out.println("Table " + name + " has been deleted.");
break;
}
}
rs.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
and I am calling the writeToPlayerDB() method in the actionListener for my GUI's JTextField as shown below:
nameField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (nameField.getText().equals(""))
{
blankName.setVisible(true);
blankName.setText("PLEASE DON'T LEAVE NAME BLANK");
}
else
{
playerName.setPlayerName(nameField.getText().toUpperCase());
WritePlayerDB wdb = new WritePlayerDB();
wdb.writeToPlayerDB();
blankNamePanel.setVisible(false);
introRuleScreen();
}
}
});
Would appreciate if i could get a hand with this as I have been stuck on it for a long time!
There's not enough information to go by to truely understand what your core problem is, how ever...
static is not a good idea, especially when you're dealing with UI elements, as you might have more then one instance of the UI and then you can no longer determine which instance of the element you're actually referencing. Better to make use of dependency injection and pass the information to the method directly.
+ "VALUES(1,2,3,4)" s not how you use PreparedStatement, see Using Prepared Statements for more details
Also...
int playerID = 0;
//...
ps.setInt(1, playerID++);
means that the player id is ALWAYS 0 (the ++ is a postfix operation; assignment first, addition second). In fact, you should avoid at all costs, manually creating record ids like this and the database should be making use of "auto incrementing" values internally. See Autogenerated keys for more details.
For simplicty, I use the H2 Database Engine for the following example. It should otherwise work with Derby, but you'll want to remove the createTables method
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
DatabaseManager db = new DatabaseManager();
db.open();
JFrame frame = new JFrame();
frame.add(new MainPane(db));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class MainPane extends JPanel {
private JTextField nameField;
private JSpinner moneyCounter;
public MainPane(DatabaseManager database) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Name: "), gbc);
gbc.gridy++;
add(new JLabel("Counter: "), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
nameField = new JTextField(10);
moneyCounter = new JSpinner(new SpinnerNumberModel(0, 0, 100, 10));
add(nameField, gbc);
gbc.gridy++;
add(moneyCounter, gbc);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
if (name.isBlank()) {
JOptionPane.showMessageDialog(MainPane.this, "Name can not be blank", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
int playerId = database.savePlayer(name, (int) moneyCounter.getValue());
List<String> results = database.getPlayerById(playerId);
StringJoiner sj = new StringJoiner("<br>", "<html>", "</html>");
for (String text : results) {
sj.add(text);
}
JOptionPane.showMessageDialog(MainPane.this, sj.toString(), "Success", JOptionPane.PLAIN_MESSAGE);
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(MainPane.this, "Failed to create player record", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(btnSave, gbc);
}
}
public class DatabaseManager {
private Connection connection;
protected void createTables() throws SQLException {
String cmd = "create table IF NOT EXISTS PLAYERINFO ("
+ "PLAYER_ID bigint GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY,"
+ "PLAYER_NAME varchar(255) not null,"
+ "PRIZE_WON int not null,"
+ "CORRECT_ANSWERS int not null"
+ ")";
try (Statement stmt = connection.createStatement()) {
stmt.execute(cmd);
}
}
public void open() throws SQLException {
if (connection != null && !connection.isClosed()) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.WARNING, null, ex);
}
}
connection = DriverManager.getConnection("jdbc:h2:~/test");
createTables();
}
public void close() throws SQLException {
if (connection == null) {
return;
}
try {
if (connection.isClosed()) {
connection = null;
}
connection.close();
} finally {
connection = null;
}
}
public int savePlayer(String name, int counter) throws SQLException {
String cmd = "insert into PLAYERINFO (PLAYER_NAME, PRIZE_WON, CORRECT_ANSWERS) values (?, ?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(cmd, Statement.RETURN_GENERATED_KEYS)) {
Random rnd = new Random();
stmt.setString(1, name);
stmt.setInt(2, rnd.nextInt(100) + 1);
stmt.setInt(3, counter);
if (stmt.executeUpdate() != 1) {
throw new SQLException("Unexpectedly modified more then one row");
}
try (ResultSet rs = stmt.getGeneratedKeys()) {
if (rs.next()) {
return rs.getInt(1);
}
}
}
throw new SQLException("Failed to create player record");
}
public List<String> getPlayerById(int id) throws SQLException {
String cmd = "select * from playerinfo where PLAYER_ID = ?";
List<String> results = new ArrayList<>(8);
try (PreparedStatement stmt = connection.prepareStatement(cmd)) {
stmt.setInt(1, id);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString("PLAYER_NAME");
int prizeWon = rs.getInt("PRIZE_WON");
int correctAnswer = rs.getInt("CORRECT_ANSWERS");
results.add(name + " won " + prizeWon + " with " + correctAnswer + " correct answers");
}
}
}
return results;
}
}
}

Unable to resolve NullPointerException in java swing application

I made a simple login page with Java Swing in Eclipse and once I run and enter the inputs I am getting an error java.lang.NullPointerException
import java.lang.String;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class trail extends JFrame {
Connection connection =null;
private JPanel contentPane;
private JTextField id;
private JPasswordField passwordField;
public static void main(String[] args) {
String jdbcURL = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String password = ".......";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trail frame = new trail();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public trail() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 519, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("username");
lblNewLabel.setBounds(94, 114, 45, 13);
contentPane.add(lblNewLabel);
id = new JTextField();
id.setBounds(246, 111, 96, 19);
contentPane.add(id);
id.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("password");
lblNewLabel_1.setBounds(94, 178, 45, 13);
contentPane.add(lblNewLabel_1);
passwordField = new JPasswordField();
passwordField.setBounds(246, 175, 96, 19);
contentPane.add(passwordField);
JButton btnlogin = new JButton("login");
btnlogin.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
try {
String query = "select * from users where username = ? and password = ?";
PreparedStatement pst=connection.prepareStatement(query);
pst.setString(1, id.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
if(count == 1)
{
JOptionPane.showMessageDialog(null, "Password and username is correct");
}
else if(count>1)
{
JOptionPane.showMessageDialog(null, "redundancy detected");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect credentials");
}
}
rs.close();
pst.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
}
});
btnlogin.setBounds(179, 259, 85, 21);
contentPane.add(btnlogin);
}
}
You have declared Connection connection =null; later on in the try block you are using like
Connection connection = DriverManager.getConnection(jdbcURL, username, password) which is altogether different Connection object. you should be using something like .
this.connection=DriverManager.getConnection(jdbcURL, username, password)
Also you can move your code in a different method like
public void initialize() {
String jdbcURL = "jdbc:postgresql://localhost:5432/your_db";
String username = "postgres";
String password = "password";
try {
this.connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
}
And call inside the constructor like
public trail() {
initialize();
....
}

Fetch data and image path from database and put them in Jtable

I am trying to fetch some data in a jtable (on click of button) and in the database i have the path of the images stored. so i want to put them in the cell of JTable. My code is very big, because it contains some other information, like when we give a proper information in the text field, then only it will fetch me the data from the database.
This program is running fine, and there is no error in it, I just want to insert photos in one of the column in the table.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class VCstVote extends JFrame implements ActionListener{
JFrame frame;
JTextField tauid, tphone;
JLabel label, auid, aphone;
JButton cls, ok, vote;
JCheckBox chkbx;
JPanel panel,panel1,panel2, panel3;
static JTable table,table2;
DefaultTableModel model1 = new DefaultTableModel();
VCstVote() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
final UIManager.LookAndFeelInfo[] plafInfos =UIManager.getInstalledLookAndFeels();
UIManager.setLookAndFeel(plafInfos[1].getClassName() );
frame = new JFrame();
frame.setSize(930, 400);
frame.setTitle("VOTE YOUR CANDIDATE");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
vote = new JButton("VOTE YOUR CANDIDATE");
label = new JLabel("CASTE YOUR VOTE");
label.setFont(new Font("Verdana", Font.BOLD, 18));
panel.add(label);
panel1 = new JPanel();
cls= new JButton("CLOSE");
panel1.add(vote);
panel1.add(cls);
panel2 = new JPanel();
auid = new JLabel("UNIQUE ID",11);
tauid = new JTextField(10);
auid.setFont(new Font("Verdana", Font.BOLD, 10));
aphone = new JLabel("PHONE", 11);
aphone.setFont(new Font("Verdana", Font.BOLD, 10));
tphone = new JTextField(10);
ok = new JButton("SUBMIT");
panel2.add(auid);
panel2.add(tauid);
panel2.add(aphone);
panel2.add(tphone);
panel3 = new JPanel( new FlowLayout(FlowLayout.LEFT, 3,3));
panel3.add(ok);
panel2.add(panel3);
String[] columnNames = {"Candidate Name", "Department Name","Year","Photo","CASTE VOTE"};
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
cls.addActionListener(this);
ok.addActionListener(this);
vote.addActionListener(this);
frame.add(scroll, BorderLayout.WEST);
frame.add(panel2,BorderLayout.EAST);
frame.add(panel,BorderLayout.NORTH);
frame.add(panel1,BorderLayout.SOUTH);
frame.validate();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action=ae.getActionCommand();
Connection conn = null ;
String cfn= null;
String cln=null;
if(action=="SUBMIT")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1="insert into vote (vuid,uphno) values(?,?)";
String query2 = "select uphno from accounts where vuid='"+tauid.getText()+"'";
String query3 = "select p.cfname, p.clname, p.deptname, l.dyear from potential p, leads l where p.cfname=l.cfname and p.clname=l.clname and p.deptname =l.deptname";
String query4 = "Select a.ufname, a.ulname from vote v, accounts a where a.uphno=v.uphno and v.vuid='"+tauid.getText()+"'";
chkbx = new JCheckBox();
PreparedStatement ps1 = conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
PreparedStatement ps3 = conn.prepareStatement(query3);
PreparedStatement ps4 = conn.prepareStatement(query4);
ResultSet rs2= null;
ResultSet rs3= null;
ResultSet rs4= null;
rs2=ps2.executeQuery();
while(rs2.next())
{
ps1.setString(1, tauid.getText());
ps1.setString(2, rs2.getString(1));
ps1.executeUpdate();
conn.commit();
}
rs4= ps4.executeQuery();
while(rs4.next())
{
cfn = rs4.getString(1);
cln = rs4.getString(2);
}
JOptionPane.showMessageDialog(null, "Hii.. "+cfn+" "+cln+" Please Select Only one Candidate for voting, otherwise you vote will not be counted..");
rs3= ps3.executeQuery();
while(rs3.next())
{
String fname= rs3.getString(1);
String lname= rs3.getString(2);
String dept= rs3.getString(3);
String year= rs3.getString(4);
model1.addRow(new Object[]{fname+" "+lname,dept,year});
table.getColumn("CASTE VOTE").setCellEditor(new DefaultCellEditor(chkbx));
}
for (int i=0;i<model1.getRowCount();i++)
{
model1.setValueAt("false", i, 3);
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null,"Please Enter correct information");
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="VOTE YOUR CANDIDATE")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1 ="select cfname,clname,deptname,luid from potential";
String test = tphone.getText();
String query2="update vote set cfname=?, clname=?, deptname=?, luid=?, votcount=1 where uphno="+test;
ResultSet rs1 = null;
PreparedStatement ps1= conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
rs1 =ps1.executeQuery();
for(int i=0;i<model1.getRowCount();i++)
{
Object st = model1.getValueAt(i,3);
String ss= st.toString();
if(ss.equals("true"))
{
rs1.next();
String fname = rs1.getString(1);
String lname = rs1.getString(2);
String dept = rs1.getString(3);
String uid = rs1.getString(4);
ps2.setString(1, fname);
ps2.setString(2, lname);
ps2.setString(3, dept);
ps2.setString(4, uid);
ps2.executeUpdate();
conn.commit();
JOptionPane.showMessageDialog(null,"Successfully registred Your Vote");
}
else{
rs1.next();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="CLOSE")
{
frame.setVisible(false);
}
}
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
new VCstVote();
}
}
Please help me out of this, I tried many websites and codes, but it seems they are only for a defined set of data and images, none of them has a code which indicates jtable fetching data from database and rendering an image.
i have the path of the images stored. so i want to put them in the
cell of JTable.
put Icon / ImageIcon to JTable (data are stored in TableModel)
is required to override getColumnClass to Icon / ImageIcon for rendering image in the JTables cell
EDIT
I tried this type of coding, but instead it is showing me the path
only.
is required to override getColumnClass to Icon / ImageIcon
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
//or
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Long.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Icon.class;
/*case 6:
return Double.class;
case 7:
return Double.class;
case 8:
return Double.class;*/
default:
return String.class;
}
}
e.g. used in code
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JTable table;
private JLabel myLabel = new JLabel("waiting");
private int pHeight = 40;
private boolean runProcess = true;
private int count = 0;
public TableIcon() {
ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
String[] columnNames = {"Picture", "Description"};
Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
// Returning the Class of each column will allow different
// renderers to be used based on Class
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model);
table.setRowHeight(pHeight);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
myLabel.setPreferredSize(new Dimension(200, pHeight));
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(myLabel, BorderLayout.SOUTH);
new Thread(this).start();
}
public void run() {
while (runProcess) {
try {
Thread.sleep(1250);
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
String lbl = "JTable Row at : " + count;
myLabel.setIcon(myIcon);
myLabel.setText(lbl);
count++;
if (count > 2) {
count = 0;
}
}
});
}
}
public static void main(String[] args) {
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}
}

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string:" "

I was trying to develop a stockManager application in java swing with MySQL .While running the code i was getting the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at org.bil.service.StockManager.addNewItem(StockManager.java:355)
at org.bil.service.StockManager.actionPerformed(StockManager.java:163)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
I am attaching the code below..Its little long....Kindly pardon..
StockManager.java
package org.bil.service;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import org.res.bil.PersonInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;
public class StockManager implements ActionListener {
ArrayList itemList;
StockManagerDAO stockManagerDAO;
// Declaration
JPanel topPanel, bottomPanel;
JScrollPane scrollPane;
JFrame frame;
JMenuBar menubar = new JMenuBar();;
JMenu menu = new JMenu();
JMenuItem menuItem;
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
Image img = kit.getImage("images/icon.JPG");
String entryDate;
int itemNo;
String itemName;
double unitPrice;
double qty;
double totalPrice;
String supplier;
String remarks;
JTextField txtEntryDate;
JTextField txtItemNo;
JTextField txtItemName;
JTextField txtUnitPrice;
JTextField txtQty;
JTextField txtTotalPrice;
JTextField txtSupplier;
JTextField txtRemarks;
JButton BttnSaveAdded;
// Main
public static void main(String[] args) {
new StockManager();
}
// Constructor
StockManager() {
frame = new JFrame("Stock Manager");
frame.setSize(680, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(screenWidth / 4, screenHeight / 4);
frame.setIconImage(img);
frame.show();
userInterface();
itemList = new ArrayList();
stockManagerDAO = new StockManagerDAO();
}
// User Interface
public void userInterface()
{
menubar.add(menu);
menu = new JMenu("Options");
menuItem = new JMenuItem("Add New Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Delete Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Search Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Sort Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("View All Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Backup Item");
menu.add(menuItem);
menuItem.addActionListener(this);
menubar.add(menu);
menu = new JMenu("Help");
menuItem = new JMenuItem("Help Contents");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("About");
menu.add(menuItem);
menuItem.addActionListener(this);
menubar.add(menu);
frame.setJMenuBar(menubar);
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
// Add Buttons To Bottom Panel
JButton addItem = new JButton("Add New Item");
JButton deleteItem = new JButton("Delete Item");
JButton searchItem = new JButton("Item");
JButton sortItem = new JButton("Sort Item");
JButton viewAllItems = new JButton("View AllItem");
JLabel label = new JLabel(
"<HTML><FONT FACE = ARIALSIZE = 2><B>Use The options below and In The Menu To Manage Stock");
// Add Action Listeners
addItem.addActionListener(this);
deleteItem.addActionListener(this);
searchItem.addActionListener(this);
sortItem.addActionListener(this);
viewAllItems.addActionListener(this);
topPanel.add(label);
bottomPanel.add(addItem);
bottomPanel.add(deleteItem);
bottomPanel.add(searchItem);
bottomPanel.add(sortItem);
bottomPanel.add(viewAllItems);
frame.getContentPane().add(topPanel, BorderLayout.NORTH);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.setResizable(false);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand() == "Add New Item") {
//totalPrice = unitPrice * qty;
// txtTotalPrice= totalPrice;
addNewItem();
}
else if (ae.getActionCommand() == "Search Item") {
searchItem();
}
else if (ae.getActionCommand() == "Sort Contacts") {
sortItems();
}
else if (ae.getActionCommand() == "Delete Item") {
deleteItem();
}
else if (ae.getActionCommand() == "View All Items") {
viewAllItemsInStock();
}
else if (ae.getActionCommand() == "About") {
JOptionPane.showMessageDialog(frame,
"About StockManager:Helps to manage the stock by adding,deleting,searching and displaying items in the stock,",null, JOptionPane.INFORMATION_MESSAGE);
} else if (ae.getActionCommand() == "Help Contents") {
showHelp();
} else if (ae.getActionCommand() == "Backup Contacts") {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showSaveDialog(frame);
FileOutputStream bfout = null;
FileInputStream bfin = null;
String filename = null;
int p;
try {
filename = chooser.getSelectedFile().getPath();
} catch (Exception e) {
}
try {
bfout = new FileOutputStream(filename + "/data.dat");
} catch (Exception e) {
}
try {
bfin = new FileInputStream("data/data.dat");
} catch (Exception e) {
}
try {
do {
p = bfin.read();
if (p != -1)
bfout.write(p);
} while (p != -1);
} catch (Exception e) {
}
}
}
private void showHelp() {
// TODO Auto-generated method stub
}
private void viewAllItemsInStock() {
/*ResultSet rs= st.executeQuery("Select * from test");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
st.close();
}
catch(Exception e) {}
JFrame tab=new JFrame();
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(300,100);
}
});
}*/
}
private void deleteItem() {
// TODO Auto-generated method stub
}
private void sortItems() {
// TODO Auto-generated method stub
}
private void searchItem() {
// TODO Auto-generated method stub
}
public void addItemFrame() {
JFrame newFrame;
newFrame = new JFrame("Add New");
newFrame.setSize(220, 250);
newFrame.setResizable(false);
newFrame.setIconImage(img);
JLabel lblEntryDate = new JLabel("Item EntryDate: ");
JLabel lblItemNo = new JLabel("Item No: ");
JLabel lblItemName = new JLabel("Item Name: ");
JLabel lblUnitPrice = new JLabel("Item UnitPrice: ");
JLabel lblQty = new JLabel("Item Qty: ");
JLabel lblTotalPrice = new JLabel("Item TotalPrice: ");
JLabel lblSupplier = new JLabel("SupplierDetails: ");
JLabel lblRemarks = new JLabel("Remarks: ");
JLabel lblEmpty1 = new JLabel("");
JLabel lblEmpty2 = new JLabel("");
txtEntryDate = new JTextField(10);
txtItemNo = new JTextField(10);
txtItemName = new JTextField(10);
txtUnitPrice = new JTextField(10);
txtQty = new JTextField(10);
txtTotalPrice = new JTextField(10);
txtSupplier = new JTextField(10);
txtRemarks = new JTextField(10);
JButton bttnAdd = new JButton("Save");
JButton bttnCancel = new JButton("Save Added!");
bttnAdd.addActionListener(this);
bttnCancel.addActionListener(this);
JPanel centerPane = new JPanel();
JPanel bottomPane = new JPanel();
centerPane.add(lblEntryDate);
centerPane.add(txtEntryDate);
centerPane.add(lblItemNo);
centerPane.add(txtItemNo);
centerPane.add(lblItemName);
centerPane.add(txtItemName);
centerPane.add(lblUnitPrice);
centerPane.add(txtUnitPrice);
centerPane.add(lblQty);
centerPane.add(txtQty);
centerPane.add(lblTotalPrice);
centerPane.add(txtTotalPrice);
centerPane.add(lblSupplier);
centerPane.add(txtSupplier);
centerPane.add(lblRemarks);
centerPane.add(txtRemarks);
bottomPane.add(bttnAdd);
bottomPane.add(bttnCancel);
centerPane.setLayout(new GridLayout(0, 2));
newFrame.getContentPane().add(centerPane, BorderLayout.CENTER);
newFrame.getContentPane().add(bottomPane, BorderLayout.SOUTH);
newFrame.setLocation(screenWidth / 4, screenHeight / 4);
newFrame.show();
}
public void addNewItem() {
addItemFrame();
entryDate = txtEntryDate.getText();
itemNo = Integer.parseInt(txtItemNo.getText());
itemName = txtItemName.getText();
unitPrice = Double.parseDouble(txtUnitPrice.getText());
qty = Double.parseDouble(txtQty.getText());
totalPrice = unitPrice * qty;
supplier = txtSupplier.getText();
remarks = txtRemarks.getText();
if (itemName.equals("")) {
JOptionPane.showMessageDialog(null, "Please enter Item name.");
}
if (txtUnitPrice.getText() == "") {
JOptionPane.showMessageDialog(null,
"Please enter UnitPrice for the item");
}
if (txtQty.getText() == "") {
JOptionPane.showMessageDialog(null,
"Please enter Quantity of item to be added");
} else {
Items item = new Items(entryDate, itemNo, itemName, unitPrice, qty,
totalPrice, supplier, remarks);
stockManagerDAO.addNewItem(item);
JOptionPane.showMessageDialog(null, "Person Saved");
}
}
}
Items.java
public class Items
{
String entryDate;
int itemNo;
String itemName;
double unitPrice;
double qty;
double totalPrice;
String supplier;
String remarks;
// default constructor
public Items()
{
entryDate ="" ;
itemNo = 0;
itemName="";
unitPrice=0;
qty=0;
totalPrice=0;
supplier="";
remarks="";
}
public Items(String entryDate,int itemNo,String itemName,double unitPrice,double qty,double totalPrice,String supplier,String remarks)
{
this.entryDate = entryDate;
this.itemNo = itemNo;
this.itemName = itemName;
this.unitPrice = unitPrice;
this.qty =qty;
this.totalPrice=totalPrice;
this.supplier=supplier;
this.remarks=remarks;
}
//getter and setter methods
}
StockManagerDAO.java
package org.bil.service;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.res.bil.PersonInfo;
class StockManagerDAO
{
private ArrayList itemList;
private String userid = "root";
private String password = "sa";
static String url = "jdbc:mysql://localhost/test";;
private Connection con;
public void StockManagerDAO()
{
itemList = new ArrayList();
getConnection(); //Create Connection to the Oracle Database
}
public Connection getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
return con;
}
/*public ArrayList searchItem(String name)
{
try {
String sql = "SELECT * FROM Item WHERE name like '%"+name+"%'";
// Create a prepared statement
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(sql);
String itemname = "";
String itemno = "";
........
while(rs.next())
{
id = rs.getInt("id");
pname = rs.getString("name");
address = rs.getString("address");
phone = rs.getInt("phone");
email = rs.getString("email");
//Create a Item object
PersonInfo person = new PersonInfo(id, pname, address, phone, email);
//Add the person object to array list
personsList.add(person);
}
}
catch(Exception e){
System.out.println(e);
}
return personsList;
}
*/
public void addNewItem(Items item) {
try
{
String sql = "INSERT INTO stock(ItemNo ,ItemEntryDate, ItemName, ItemUnitPrice, ItemQty, ItemTotalPrice,ItemSupplier, ItemRemarks) VALUES (?,?,?,?,?,?,?,?) ";
// Create a Preparedstatement
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,item.getItemNo());
ps.setString(2, item.getEntryDate());
ps.setString(3, item.getItemName());
ps.setDouble(4, item.getUnitPrice());
ps.setDouble(5, item.getQty());
ps.setDouble(6, item.getTotalPrice());
ps.setString(7, item.getSupplier());
ps.setString(8, item.getRemarks());
ps.executeUpdate();
}
catch(Exception e){
System.out.println(e);
}
// TODO Auto-generated method stub
}
}
..Please help me...
It looks like you are trying to parse an empty string ("") as an integer (in Integer.parseInt(txtItemNo.getText()) in StockManager.addNewItem()).
You will either need to ensure that the contents of txtItemNo is not empty or, better yet, catch the NumberFormatException when an invalid string is parsed.
it means that your txtItemNo has no text, check for it before you parse it and display an error when it's invalid (or catch the exception and display the error in the catch block)

corejava Project help needed

I'm Riya a B.Tech. student and i have to make a corejava project on the topic COLLEGE MANAGEMENT SYSTEM . I have created the required database using MS Access. I m facing problem in a code which i m attaching here. Actually i want to update a data in the data base so i have made 2 frames in one of them Roll no. is asked when it is entered then the 2nd frame opens and asks Enter Marks to be updated...when i enter the marks to be updated then a dialogue box opens shoing "Marks Updated Successfully". Till here i don't have any problem..the problem is when i open the database i see that actually the Marks is not updated there.So please please please somebody help me solving this problem.
The code is as follows:
1ST FRAME
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class MyFrame03 extends JFrame implements ActionListener {
JLabel l1;
JTextField t1;
JPanel p1, p2;
JButton b1;
Connection con;
PreparedStatement pst;
String s1;
MyFrame03() {
setLayout(new GridLayout(4, 1));
setTitle("Enter Data Required");
setBackground(Color.blue);
l1 = new JLabel("Roll no");
t1 = new JTextField(12);
p1 = new JPanel();
p2 = new JPanel();
b1 = new JButton("SUBMIT");
p1.add(l1);
p1.add(t1);
p2.add(b1);
add(p1, "Center");
add(p2, "South");
b1.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null)
System.out.println("Connection Established");
}
catch (Exception e) {
System.out.println("exception");
}
}
public void actionPerformed(ActionEvent e1) {
if (e1.getSource() == b1) {
s1 = t1.getText();
try {
pst = con.prepareStatement("insert into stud values(?)");
pst.setString(1, s1);
pst.executeUpdate();
con.commit();
con.close();
}
catch (SQLException e) {
System.out.println("except1");
}
MyFrame04 m1 = new MyFrame04(s1);
dispose();
}
}
public static void main(String s[]) throws SQLException {
MyFrame03 m1 = new MyFrame03();
}
}
2nd FRAME
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class MyFrame04 extends JFrame implements ActionListener {
JLabel l1;
JTextField t1;
JPanel p1, p2;
JButton b1;
String s1, s2;
Connection con;
PreparedStatement pst;
public MyFrame04(String s1) {
this.s1 = s1;
setLayout(new GridLayout(4, 1));
setTitle("Update Marks");
setBackground(Color.blue);
l1 = new JLabel("Enter Marks");
t1 = new JTextField(12);
b1 = new JButton("SUBMIT");
p1 = new JPanel();
p2 = new JPanel();
p1.add(l1);
p1.add(t1);
p2.add(b1);
add(p1, "Center");
add(p2, "South");
b1.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null)
System.out.println("Connection Established");
}
catch (Exception e) {
System.out.println("exception");
}
}
public void actionPerformed(ActionEvent e1) {
if (e1.getSource() == b1) {
s2 = t1.getText();
try {
pst = con.prepareStatement("UPDATE stud set Marks=? WHERE Roll no=?");
pst.setString(1, s2);
pst.setString(2, s1);
pst.executeUpdate();
con.commit();
con.close();
}
catch (SQLException e) {
System.out.println("except1");
}
JOptionPane.showMessageDialog(this, "Marks updated succesfully");
dispose();
}
}
}
Thankyou
Does your database access code work without Swing? The simplest way to see this would be something like:
class HelloDatabase {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:dsn3");
if (con != null) {
int marks = 1, roll = 1; // or whatever (your data here)
System.out.println("Connection Established");
PreparedStatement pst = con.prepareStatement("UPDATE stud SET marks=? WHERE roll_num=?");
pst.setString(1, marks);
pst.setString(2, roll);
pst.executeUpdate();
con.commit();
con.close();
}
}
catch (Exception e) {
System.out.println("exception");
}
}
}
If this gets a handle and accesses your database properly, you're in luck.
By the way -- and this may actually be your issue -- I noticed that your SQL query from the original post had an ambiguity in it:
UPDATE stud set Marks=? WHERE Roll no=?
"Roll no" would not get recognized a valid SQL field, as far as I understand -- these should be a single 'word' (like 'roll', 'roll_num' or even 'RollNum' -- but I don't think a name like 'Roll no' would work here.)

Categories