Hi want to to create a JTable with SQLite Database. The data should come from a SQLite database and are stored in this . Now new details to be added by typing in a text field . However, I get the error message : "java.sql.SQLException: near "(": syntax error"
What´s wrong?
public class SQLite {
public static DefaultTableModel model = new DefaultTableModel();
private static JTextField fieldID;
private static JTextField fieldName;
private static JTextField fieldAge;
private static JTextField fieldAddress;
private static JTextField fieldSalary;
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
c.commit();
JFrame f = new JFrame();
f.setLayout(new GridLayout(5,1));
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
fieldID = new JTextField("ID");
fieldName = new JTextField("Name");
fieldAge = new JTextField("Age");
fieldAddress = new JTextField("Address");
fieldSalary = new JTextField("Salary");
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
stmt.executeUpdate(sql);
JTable table = new JTable(model);
f.add( new JScrollPane( table ) );
model.addColumn("id");
model.addColumn("name");
model.addColumn("age");
model.addColumn("address");
model.addColumn("salary");
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
model.addRow(new Object[] {id, name, age, address, salary});
}
/**JTextField feldID = new JTextField("ID");
JTextField feldName = new JTextField("Name");
JTextField feldAge = new JTextField("Age");
JTextField feldAddress = new JTextField("Address");
JTextField feldSalary = new JTextField("Salary");
**/
f.pack();
f.setVisible( true );
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
Here is your problem :
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
They're read as litterals and not as a reference to a getter.
Here is what you'll have to replace it with by using concatenation.
"VALUES ("+fieldID.getText()+","+feldName.getText()+","+Age.getText()+","+feldAddress.getText()+","+feldSalary.getText()+");";
Use a PreparedStatement. It is easier to code and maintain and will manage the delimiters for you:
String sql = "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) VALUES (?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, fieldID.getText() );
stmt.setString( 2, fieldname.getText() );
stmt.setString( 3, ... );
stmt.setString( 4, ... );
stmt.setString( 5, ... );
stmt.executeUpdate();
but now i get the java sql Exception: "no such column: ID"
Well, the message is self explanatory. There is no "ID" column. We can't help you with that because only you know the proper names of the columns since you are the one that created the database.
Related
I wrote a program in java to retrieve images and text data from a table. Everything is right, only when i try to retrieve an image(Blob) from the table, i get an exhausted result set error.I tried google it, but the explanation was fa too condensed. Can anyone help me with this? I will appreciate a nice explanation.
Here is the code
try {
Class.forName(classforname);
Connection con = DriverManager.getConnection(Connectionurl, username, password);
String sql = "Select * from teacherdata where teachername='" + tf1.getText() + "'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
rs.next();
String thename = rs.getString("teachername");
String sub1, sub2, sub3, sub4;
sub1 = rs.getString("sub1");
sub2 = rs.getString("sub2");
sub3 = rs.getString("sub3");
sub4 = rs.getString("sub4");
String sql2 = "select tid,tpic from teacherimages where teachername='" + tf1.getText() + "'";
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery(sql2);
rs2.next();
String Tid = rs2.getString("tid");
Blob b = rs.getBlob("tpic");
byte barr
[] = new byte[(int) b.length()]; //an array is created but contains no data
barr = b.getBytes(3, (int) b.length());
Image im = jInternalFrame1.getToolkit().createImage(barr);
ImageIcon icon = new ImageIcon(im);
JLabel label = new JLabel(icon);
Object[] row = {
thename,
sub1,
sub2,
sub3,
sub4,
b,
Tid,
icon
};
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
jTable1.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SearchBox.class.getName()).log(Level.SEVERE, null, ex);
}
You are not checking the return value of next on the ResultSet.
Please consider changing your code to
if(result.next()){
// the logic
}
EDIT
Further on the code change , please check that your tables are not empty. If your tables are empty you will not return values.
The error Exhausted Resultset set occurs when you attempt to access the result set after iterating or not checking if the result set returns data
while (resultSet.next()) {
//result set logic
}
//
resultset.getString[1] //<- will throw error Exhausted Resultset
Good day . I've the following code which i'm trying to make work . I have to read the content of a text file , which contains questions and save it to the database testsystem .
The main problem that i'm facing is that it's not inserted in the database. and i'm not sure whether it is reading the textfile or not.
any help will be glady appreciated
JFrame and main
public class StudentTestSystems {
public static void main(String[] args) {
try {
Lecturer panel = new Lecturer();
panel.setVisible(true);
panel.setLocationRelativeTo(null);
panel.setResizable(false);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Lecturer class
public class Lecturer extends JFrame implements ActionListener {
Font font = null;
private JTextField fileField;
private JButton uploadBtn;
private JLabel message;
private JPanel panel;
public Lecturer() {
super("LECTURE MENU");
this.setSize(500, 270);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
font = new Font("Times New Roman", Font.BOLD, 14);
panel = new JPanel();
panel.setLayout(null);
panel.setOpaque(true);
fileField = new JTextField();
fileField.setFont(font);
fileField.setBounds(130, 110, 200, 25);
Font font2 = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 12);
message = new JLabel("Type in the file name with it's extension. eg: File.txt");
message.setFont(font2);
message.setBounds(130, 140, 280, 25);
message.setOpaque(true);
uploadBtn = new JButton("UPLOAD");
uploadBtn.setFont(font);
uploadBtn.setBounds(340, 110, 95, 21);
panel.add(fileField);
panel.add(uploadBtn);
panel.add(message);
add(panel);
/////// register event
uploadBtn.addActionListener(this);
exit.addActionListener(this);
}
public void actionPerformed(ActionEvent ev) {
String file = fileField.getText();
SetGetQuestionFileName setGet = new SetGetQuestionFileName(file);
FileInputStream fis = null;
PreparedStatement preparedStmt = null;
try {
String myUrl = "jdbc:mysql://localhost:3306/testsystem";
Connection conn = DriverManager.getConnection(myUrl, "root", "cput");
if (ev.getActionCommand().equals("UPLOAD")) {
File filePathString = new File(file);
fis = new FileInputStream(filePathString);
if (fileField.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "File field can't be empty. Try again", "ERROR", JOptionPane.INFORMATION_MESSAGE);
} else {
if (filePathString.exists() && filePathString.isFile()) {
try {
// the mysql insert statement
String query = " insert into users (category_questions, questions, quest_opt_a, , quest_opt_b, , quest_opt_c, quest_opt_d, correct_option_answer )"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, "JDBC");
preparedStmt.setString(2, fileField.getText());
preparedStmt.setAsciiStream(3, fis, (int) filePathString.length());
//preparedStmt.setString (3, "a");
preparedStmt.setString(4, "b");
preparedStmt.setString(5, "c");
preparedStmt.setString(6, "d");
preparedStmt.setString(7, "a");
preparedStmt.executeUpdate();
// execute the preparedstatement
preparedStmt.executeUpdate();
// myfile.closing();
conn.close();
JOptionPane.showMessageDialog(null, "File successfuly uploaded", "INFORMATION", JOptionPane.INFORMATION_MESSAGE);
fileField.setText("");
} catch (Exception ex) {
} finally {
preparedStmt.close();
fis.close();
conn.close();
}
} else {
JOptionPane.showMessageDialog(null, "File coudn't be found. Do check file name.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}
}
}
} catch (Exception ex) {
}
if (ev.getActionCommand().equals("LOGOUT")) {
System.exit(0);
}
}
}
SetQuestionFileName class
public class SetGetQuestionFileName {
String myfile;
public SetGetQuestionFileName(String file) {
setFileName(file);
}
public void setFileName(String file) {
myfile = file;
}
public String getFileName() {
return myfile;
}
}
Here a short version on how you can read a file (line by line):
Scanner scanner = new Scanner(filename);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
}
This is your query. There where too many , or empty column names and the number of columns and ? does not match:
String query = " insert into users (
category_questions,
questions,
quest_opt_a,
, // empty column name
quest_opt_b,
, // empty column name
quest_opt_c,
quest_opt_d,
correct_option_answer
)" + " values (?, ?, ?, ?, ?)"; // you have 7 columns (without the empty ones) but only 5 ?
Here a reformatted version of your query. I just removed the , and added 2 ?
String query = "INSERT INTO users (
category_questions,
questions,
quest_opt_a,
quest_opt_b,
quest_opt_c,
quest_opt_d,
correct_option_answer
) VALUES (?, ?, ?, ?, ?, ?, ?)";
Now I am trying to understand the values you want to add:
preparedStmt.setString(1, "JDBC"); // so JDBC is your category ?
preparedStmt.setString(2, fileField.getText()); // I guess this should be the question?
preparedStmt.setString(3, "a"); // according to the column names this needs to be option A
preparedStmt.setString(4, "b"); // option b
preparedStmt.setString(5, "c"); // option c
preparedStmt.setString(6, "d"); // option d
preparedStmt.setString(7, "a"); // answer
So far so good. If I interpreted the column names correctly, this should work. The only thing left is now to get the real question text for column 2 (from the file).
I don't know how your file looks like, so I can just give you an example:
textfile in this format: question? answerA, answerB, answerC, answerD, correctAnswer
-------------------------------------------------------------------------------------
What is the color of the sun? pink, blue, yellow, green, c
What is the smallest number? 3, 1, 7, 200, b
And this would be how you could read the file and fill the database all at once:
// prepare the query
String query = "INSERT INTO users (
category_questions,
questions,
quest_opt_a,
quest_opt_b,
quest_opt_c,
quest_opt_d,
correct_option_answer
) VALUES (?, ?, ?, ?, ?, ?, ?)";
// load the file
Scanner scanner = new Scanner(filename);
// read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] questionAnswer = line.split("?")[ // line.split["?"] will split the line into two strings, right at the ? and put those two strings into an array.
String question = questionAnswer[0] // so [0] will access the first element in that array - the question
String[] answers = questionAnswer[1].split(","); // now we split the string after the ? into many strings divided by comma
preparedStmt.setString(1, "JDBC");
preparedStmt.setString(2, question);
preparedStmt.setString(3, answers[0]);
preparedStmt.setString(4, answers[1]);
preparedStmt.setString(5, answers[2]);
preparedStmt.setString(6, answers[3]);
preparedStmt.setString(7, answers[4]);
preparedStmt.executeUpdate();
}
There are many ways to read the line from your text file and split it into question and answer. It depends on the file you read from and how it is formatted.
FIY: you execute preparedStmt.executeUpdate(); twice at the end :)
I have created a database and a set of table using JDBC and SQLite in Eclipse.
I am trying to update the table using the following code:
public static void update()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM CUSTOMERS;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully");
}
As far as I can understand the SQL syntax I m using says:
update the table customers2 and set the address as Byron where phone =2
But am getting the following error:
java.sql.SQLException: no such column: Byron
Which tells me it is interpreting my request as asking to alter the column named Byron, which is not what I believe the code to be saying?
As per SQL syntax, varchar values should be used with single quotes so update this:
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
to
String sql = "UPDATE CUSTOMERS2 set ADDRESS = 'Byron' WHERE PHONE=2;";
If you don't use the single quotes, SQL assumes that you are trying to set the value using a different column and hence it throws the error:
java.sql.SQLException: no such column: Byron
ADVICE: Use PreparedStatment for dynamic parameter queries
PreparedStatement stmt;
String sql = "UPDATE CUSTOMERS2 set ADDRESS=? WHERE PHONE=?";
stmt = c.prepareStatement(sql);
stmt.setString(1, "Byron");
stmt.setInt(2, 2);
stmt.executeUpdate();
I have a Jtable (tableSummary).
I need to format 2 columns of the table so it's content is in DECIMAL form (e.g. 1,400.00)
How can i do it?
here's my code for the table:
private void tableMarketMouseClicked(java.awt.event.MouseEvent evt) {
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = ?";
try {
//add column to the table model
model.setColumnCount(0); //sets the column to 0 para ig utro click, dili mapun-an ang columns
model.setRowCount(0); //sets the row to 0 para ig utro click, dili mapun-an ang rows
model.addColumn("C NO");
model.addColumn("MARKET");
model.addColumn("BORROWER");
model.addColumn("LOAN");
model.addColumn("START");
model.addColumn("DAILY");
model.addColumn("EXPIRY");
//model.addColumn("BALANCE");
int row = tableMarket.getSelectedRow();
pst = conn.prepareStatement(sql);
pst.setString(1, tableMarket.getModel().getValueAt(row, 0).toString());
rs = pst.executeQuery();
while(rs.next()){
String id = rs.getString(1);
String market = rs.getString(2);
String name = rs.getString(3);
String amt = rs.getString(4);
String start = rs.getString(5);
String daily = rs.getString(6);
String expiry = rs.getString(7);
//String area = rs.getString(3);
model.addRow(new Object[]{ id, market, name, amt, start, daily, expiry});
}
tableSummary.setModel(model);
renderer.setHorizontalAlignment( JLabel.RIGHT );
renderer2.setHorizontalAlignment( JLabel.CENTER );
tableSummary.getColumnModel().getColumn(0).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(4).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(6).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(3).setCellRenderer( renderer );
tableSummary.getColumnModel().getColumn(5).setCellRenderer( renderer );
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
the columns, amt and daily are the columns i need to be formatted.
Thanks in Advance!
As kleopatra already suggested in her comments
The conversion from Object to a String representation (or any other representation) is the task of the renderer. Your TableModel should just contain the objects
Create and set the appropriate renderer on your JTable (for example by calling JTable#setDefaultRenderer or overriding JTable#getCellRenderer)
As renderer for your Number instances you can use one which uses the NumberFormat for formatting as shown in the answer of Samir
NumberFormat formatter = new DecimalFormat("#,###.00");
String str = formatter.format(1400);
System.out.println(str);
Someone has suggested to use prepared statement but I don't know how to use it. What changes do I have to do in my code?
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con = DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt = con.createStatement();
System.out.println("statement is created");
// System.out.println(Integer.parseInt(cbregn.getSelectedItem().toString()));
String qry = " UPDATE Registration1 SET RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ;
stmt.executeUpdate(qry);
JOptionPane.showMessageDialog(null,"RECORD IS UPDATED SUCCESSFULLY ");
System.out.println("QUERY");
// cbregn.setEditable(false);
cbnm.setEditable(false);
tfplace.setEditable(false);
tfkul.setEditable(false);
tfgotra.setEditable(false);
tfswami.setEditable(false);
taraddr.setEditable(false);
tfpcd.setEditable(false);
tfstdcode.setEditable(false);
tftele.setEditable(false);
tfmno.setEditable(false);
tfemail.setEditable(false);
tfweb.setEditable(false);
tfedu.setEditable(false);
tfbrch.setEditable(false);
cbbldgrp.setEditable(false);
con.close();
stmt.close();
}
// catch(SQLException eM)
// {
// JOptionPane.showMessageDialog(null,"RECORD IS NOT FOUND ");
// }
catch(Exception et)
{
et.printStackTrace();
// System.out.println("error:"+et.getMessage());
}
see example
Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack. Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user. This entails using functions that escape all of the necessary trouble characters, such as the single quote, double quote, and backslash characters. This is unnecessary when dealing with prepared statements. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.
In your code instead of this:
String qry= " UPDATE Registration1 set RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ;
stmt.executeUpdate(qry);
try this:
String qry= " UPDATE Registration1 set RegistrationNo = ?,SeniorPerson = ?, NativePlace = ?,Kul = ?, Gotra = ?,KulSwami = ?, ResidensialAddress = ?, PinCode = ?, STDcode = ?,TelephoneNo = ?, MobileNo = ?, Email = ?,Website =?,Education =?,Branch =?,BloodGroup =? where SeniorPerson=?" ;
PreparedStatement updateQry = con.prepareStatement(qry);
updateQry.setString(1,cbregn.getSelectedItem());
updateQry.setString(2,cbnm.getSelectedItem());
updateQry.setString(3,tfplace.getText());
updateQry.setString(4,tfkul.getText());
updateQry.setString(5,tfgotra.getText());
updateQry.setString(6,tfswami.getText());
updateQry.setString(7,taraddr.getText());
updateQry.setString(8,tfpcd.getText());
updateQry.setString(9,tfstdcode.getText());
updateQry.setString(10,tftele.getText());
updateQry.setString(11,tfmno.getText());
updateQry.setString(12,tfemail.getText());
updateQry.setString(13,tfweb.getText());
updateQry.setString(14,tfedu.getText());
updateQry.setString(15,tfbrch.getText());
updateQry.setString(16,cbbldgrp.getSelectedItem());
updateQry.setString(17,cbnm.getSelectedItem().toString());
updateQry.executeUpdate():
public class UpdatesRecords{
public static void main(String[] args) {
System.out.println("Updates Records Example through Prepared Statement!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
String sql = "UPDATE movies SET title = ? WHERE year_made = ?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1,"Sanam We wafafa");
prest.setInt(2,2005);
prest.executeUpdate();
System.out.println("Updating Successfully!");
con.close();
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
please use above code as reference and change your code