MsAccess SQL Exception Too few parameters - java

Currently making a java program that grabs data off of a MSAccess Database and some of these errors are extremely frustrating. I keep getting this SQL.Exception : Too few parameters. Expected 1 error on the last remaining bugs in this program.
Little background on the db: It has 3 tables (A player table (11 columns), a team table (3 columns), and an Opponent table (6 columns).
These are both of the functions and I am fairly certain the problem lies in here somewhere
conn = Connect.ConnectDB();
String sql = "insert into Player ("+"PlayerLastName,"+"PlayerFirstName,"+"Position)"+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeQuery();
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
or this function
String sql = "select * from Player where PlayerLastName = " +txtid.getText()+ "";
String pine = null;
try{
pst = conn.prepareStatement(sql);
ResultSet res;
res = pst.executeQuery();
pine.equalsIgnoreCase(jTable1.getModel().getValueAt(rowsu, 10).toString());
while(res.next()){
JOptionPane.showMessageDialog(null, txtname + " " + txtid.getText() + " has a total of " +"4");//+ pine);//res.getInt("Penalties") );
}
UpdateJTable();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

For one thing, it looks like you're missing single quotes around the last name in the insert statement.
There may be other errors as well, that's just the first thing I noticed.
This should be pretty easy to debug if you just log the sql string before executing it.
EDIT
I think your calls to setString() are also a problem. Here is how you should do this:
conn = Connect.ConnectDB();
String sql = "insert into Player (PlayerLastName, PlayerFirstName, Position) values(?, ?, ?)";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
pst.execute();
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

Related

JDBC error : can not issue executeupdate() for selects

Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.

How to delete a MySQL database in java selected record (row)

How to delete a MySQL database selected record (row)
I use this code
connectDB();
try{
java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
String sql = "Delete FROM user WHERE No= "+txt_search_code.getText();
pstmt = con.prepareStatement(sql);
pstmt.setString(1,txt_search_code.getText());
pstmt.execute();
JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");
} catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
closeDB();
but it get an error like this -
java.sql.SQLException:Parameter index out of range(1>number of
parameters,which is 0)
So how can I fix this probleam....(Examples please)
Thanks
Try this:
connectDB();
try{
java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
stmt.setString(1,txt_search_code.getText());
stmt.execute();
JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");
} catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
closeDB();
The problem is you are not using quotation marks around the string you want to delete.
It should be the following:
string sql = "Delete FROM user WHERE No= '" + txt_search_code.getText()+ "'";
Sql is now tring to convert to numerics.

java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available

I am a newbie assigned to build a hostel management application using HikariPool connection. Now, i sometimes get this error java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available and once it happens, it messes up my application data. For instance, in my code below, i call the function paymentRecord() in my AssignRoom() to execute after a room is assigned.
I open and close connections in each functions(AssignRoom() and paymentRecord()) but sometimes, one of the functions fail to execute. It is either AssignRoom() executes correctly and paymentRecord() fails to execute or vice versa.
My code may be very bad but i am newbie trying to learn.
PS: Now i never had this issue when i was testing the application with good internet connection , but my Client did report this and he mostly has internet connectivity problem.
I sometimes think the internet connection might be a factor to my problem, if so why do i deal with this please?
Assigning Room
public void AssignRoom(){
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
conn = DBConnection.getConn();
String query = "Insert into AssignRoom(Floor,RoomNumber,Student,DateAssigned) values (?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, Floor.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setString(3, FindStd.getSelectedItem().toString());
pst.setDate(4, sqldate);
pst.execute();
if(seats.getText().equals("0")){
JOptionPane.showMessageDialog(null, "Room is fully occupied");
}
else
{
JOptionPane.showMessageDialog(null, "Room Successfully Assigned");
UpdateAvailableBeds();
paymentRecord();
conn.close();
JOptionPane.showMessageDialog(null, "Please wait...Processing payment");
navToPayment();
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
Payment Record
public void paymentRecord()
{
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
System.out.println("Cheking "+sqldate);
System.out.println("Cheking "+FindRoom.getSelectedItem().toString());
System.out.println("Cheking "+FindStd.getSelectedItem().toString());
conn = DBConnection.getConn();
String query = "Insert into PaymentRecords(Student_Name,Room_Number,DateAssigned,Total_Amount,Paid,Balance) values(?,?,?,?,?,?)";
String sql = "select Price from Rooms where RoomNumber =" +FindRoom.getSelectedItem()+ " and Floor ='"+Floor.getSelectedItem().toString()+"'";
PreparedStatement pst = conn.prepareStatement(query);
PreparedStatement pst1 = conn.prepareStatement(sql);
// ResultSet rs = pst.executeUpdate(query);
ResultSet rs1 = pst1.executeQuery(sql);
while(rs1.next())
{
FullAmount = rs1.getString("Price");
Price = Float.parseFloat(FullAmount);
Rem = Float.parseFloat(AmtPaid.getText());
Balance = Price - Rem;
System.out.println("Cheking "+FullAmount);
}
pst.setString(1, FindStd.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setDate(3, sqldate);
pst.setString(4, FullAmount);
pst.setString(5, AmtPaid.getText());
pst.setFloat(6, Balance);
pst.execute();
pst1.execute();
conn.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}

Syntax Error in insert upto? MSAccess

I am trying to insert data a user enters into a jtextfield into an msaccess database. When I try to execute my sql statement I get an error stating Syntax error in INSERT INTO statement.
I checked my sql statement and tried a few different things but cannot seem to find any kind of syntax error.
conn = Connect.ConnectDB();
String sql = "insert into Team ("
+"TeamID,"
+"TeamCity,"
+"TeamMascot,"
+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Entry " + txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
The error is the extra comma and no closing parenthesis before the keyword values
String sql = "insert into Team ("
+"TeamID,"
+"TeamCity,"
+"TeamMascot," // <<== HERE, change comma into closing parenthesis
By the way, your statement is vulnerable with SQL Injection. You can avoid it if you parameterized the values. Eg,
String sql = "insert into Team (TeamID,TeamCity,TeamMascot) values (?, ?, ?, ?)"
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
PreparedStatement

How to insert the same record into two different table in java?

How can I insert records into two different table? I made two sql statement and it won't work.
private void cmdsubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String sql = "Insert into customer (Customer_ID,First_Name,Last_Name,Birthdate,Gender,Occupation,Address,Email,Contact,Status,Income,Amount,Term,Interest,Date_Applied,Purpose,Other) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText());
pst.setString(3, txtlname.getText());
pst.setString(4,((JTextField)birthdate.getDateEditor().getUiComponent()).getText());
String gender = cmbgender.getSelectedItem().toString();
pst.setString(5, gender);
pst.setString(6, txtoccupation.getText());
pst.setString(7, txtaddress.getText());
pst.setString(8, txtemailadd.getText());
pst.setString(9, txtcontact.getText());
String status = cmbstatus.getSelectedItem().toString();
pst.setString(10, status);
String income = cmbincome.getSelectedItem().toString();
pst.setString(11,income);
pst.setString(12, txtamount.getText());
String period = cmbperiod.getSelectedItem().toString();
pst.setString(13, txtloan.getText() + " " + period);
pst.setString(14, txtinterest.getText());
pst.setString(15, ((JTextField)datechooser.getDateEditor().getUiComponent()).getText());
String purpose = cmbpurpose.getSelectedItem().toString();
pst.setString(16, purpose);
pst.setString(17, txtother.getText());
Double balance = Double.parseDouble(txtamount.getText()) * Double.parseDouble(txtinterest.getText());
String s = "Insert into payments (Customer_ID,Customer_Name,Amount,Interest,To_Pay) values (?,?,?,?,?)";
pst = conn.prepareStatement(s);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText()+","+txtlname.getText());
pst.setString(3, txtamount.getText());
pst.setString(4, txtinterest.getText());
pst.setString(5, balance.toString());
pst.execute();
JOptionPane.showMessageDialog(null, "Record Save");
Menu menu = new Menu();
this.setVisible(false);
menu.setVisible(true);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem appears to be that you aren't calling pst.execute() before you call this line:
pst = conn.prepareStatement(s);
This is overwriting your previous pst variable; creating a new PreparedStatement.
I'm not entirely sure about that API, but it seems like you have one execute for two statements. Also, you should consider making a function if a good chunk of the code is exactly the same. Less places to maintain

Categories