MySQL PreparedStatement: Parameter index out of range - java

I'v searched during one hour trough stackoverflow and couldn't find an answer to my problem (Well, there's people having the same error, but not exactly like mine).
So here's the code:
public synchronized static void setAllData(String player, String xp, String lvl, String coins, String won, String lost, String kills, String deaths, String redput, String blueput, String time)
{
try
{
PreparedStatement sql =
connection.prepareStatement("UPDATE `" + Main.table + "` SET `xp` = ?, lvl` = ?, `towercoins` = ?, `won` = ?, `lost` = ?, `kills` = ?, `deaths` = ?, `redput` = ?, `blueput` = ?, `time` = ? WHERE `player` = ?;");
sql.setString(1, xp);
sql.setString(2, lvl);
sql.setString(3, coins);
sql.setString(4, won);
sql.setString(5, lost);
sql.setString(6, kills);
sql.setString(7, deaths);
sql.setString(8, redput);
sql.setString(9, blueput);
sql.setString(10, time);
sql.setString(11, player);
sql.executeUpdate();
sql.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And i have this error every time:
Java.sql.SQLException: Parameter index out of range (2 > number of
parameters, which is 1).
I don't get it since all parameters are here etc... so why ?
Thanks a lot :)

seems like you missing the opening quote on this statement.
SET `xp` = ?, lvl` = ?,

it would be like this
connection.prepareStatement("UPDATE " + Main.table + " SET xp = ?, lvl = ?, towercoins = ?, won = ?, lost = ?, kills = ?, deaths = ?, redput = ?, blueput = ?, time = ? WHERE player = ?;");

Related

Importing .csv into SQLite in Java

I have to write a programm that automatically reads out of my .csv and puts the data into my SQLite. This code fills up the first line in my table, which I created before.
How to I skip/go to the next line, to fill it up?
I guess its something in the loop, but Im not sure what to change...
(I skipped the first line, because it contains the columns.)
Code:
public static void read()
{
String csv = "C:\\Users\\schneider\\Desktop\\Schneider\\Excel\\DienstbarkeitenTabelle.csv";
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
int currentLine = 0;
Connection conn = null;
try
{
conn = DriverManager.getConnection("jdbc:sqlite:C:/sqlite/db/tollerName");
PreparedStatement prep = conn.prepareStatement("insert into tollerName(Bauprojekt, Bauprojektnummer, Auftragsnummer,Trassierung, JahrSAP, ProjektnummerSPA, Anlagenzahl, AktuelleLeitungslaenge, VorgaengeZumProjekt, VertraegeZumProjekt, Firma, Flurst, Blatt, Verf, Anl, RE, LL, BreiteSS, FlaecheRA, Entsch, Haupteigentuemer, Gemarkung, Grundbuchamt, Strase, Hausnummer, Hausnummerzusatz, Ort, plz, VkWert, prozentBPD, Anlage, GFR, GBA, Empfaenger, Bank, IBAN, BIC, von, an, JahrDerVergabe, Zahlungsgrund, Netto, Aufwand, Umsatzsteuer) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
br = new BufferedReader(new FileReader(csv));
while((line = br.readLine()) != null)
{
if(currentLine > 0)
{
String[] table = line.split(csvSplitBy);
prep.setString(1, (table[0]));
prep.setString(2, (table[1]));
prep.setString(3, (table[2]));
prep.setString(4, (table[3]));
prep.setString(5, (table[4]));
prep.setString(6, (table[5]));
prep.setInt(7, Integer.parseInt(table[6]));
prep.setDouble(8, Double.parseDouble(table[7]));
prep.setInt(9, Integer.parseInt(table[8]));
prep.setInt(10, Integer.parseInt(table[9]));
prep.setString(11, (table[10]));
prep.setString(12, (table[11]));
prep.setString(13, (table[12]));
prep.setString(14, (table[13]));
prep.setString(15, (table[14]));
prep.setString(16, (table[15]));
prep.setDouble(17, Double.parseDouble(table[16]));
prep.setDouble(18, Double.parseDouble(table[17]));
prep.setDouble(19, Double.parseDouble(table[18]));
prep.setDouble(20, Double.parseDouble(table[19]));
prep.setString(21, (table[20]));
prep.setString(22, (table[21]));
prep.setString(23, (table[22]));
prep.setString(24, (table[23]));
prep.setString(25, (table[24]));
prep.setString(26, (table[25]));
prep.setString(27, (table[26]));
prep.setString(28, (table[27]));
prep.setDouble(29, Double.parseDouble(table[28]));
prep.setDouble(30, Double.parseDouble(table[29]));
prep.setString(31, (table[30]));
prep.setString(32, (table[31]));
prep.setString(33, (table[32]));
prep.setString(34, (table[33]));
prep.setString(35, (table[34]));
prep.setString(36, (table[35]));
prep.setString(37, (table[36]));
prep.setString(38, (table[37]));
prep.setString(39, (table[38]));
prep.setString(40, (table[39]));
prep.setString(41, (table[40]));
prep.setDouble(42, Double.parseDouble(table[41]));
prep.setDouble(43, Double.parseDouble(table[42]));
prep.setDouble(44, Double.parseDouble(table[43]));
prep.execute();
conn.commit();
}
currentLine++;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(br == null)
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("müsste feddich sein");
}
You initialize currentLine to 0, the first time you pass in your loop the condition if(currentLine > 0) is false, that's why the first line is not inserted.
unless you have deleted some important part of your code the test is useless. currenltLine is only incremented starting from 0, it can never be negative nor null.

How to get a generated UUID type using JDBC getGeneratedKeys?

This is specific to MySQL and UUID type of id for which I am using uuid() function of MySQL itself. It's giving me not null resultSet, but next() value is always empty.
Following is the code:
String insertQuery = "INSERT INTO fixtures "
+ "(id, whatever1, whatever2, whatever3, whatever4, "
...
+ "created_at) "
+ "VALUES(UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
.
.
.
preparedStatement.setDate(23, sqlDate);
preparedStatement.executeUpdate();
ResultSet keysResultSet = preparedStatement.getGeneratedKeys();
System.out.println(keysResultSet); // com.mysql.cj.jdbc.result.ResultSetImpl#6892b3b6
if(keysResultSet != null && keysResultSet.next()){
System.out.println("Generated Emp Id: "+keysResultSet.getString("id"));
} else {
System.out.println("No KEYS GENERATED");
}
There is no key generated, but actually provided:
So either leave the creation to the database:
String insertQuery = "INSERT INTO fixtures "
+ "(whatever1, whatever2, whatever3, whatever4, "
...
+ "created_at) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, "
+ "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
As I am not aware of how to easily achieve a UUID on the MySQL side, I would suggest the original solution with a UUID on java side:
String insertQuery = "INSERT INTO fixtures "
+ "(id, whatever1, whatever2, whatever3, whatever4, "
...
+ "created_at) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, "
+ "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
UUID id = UUID.randomUUID();
preparedStatement.setString(1, id.toString());
Getting the UUID then becomes irrelevant.
For SQL Server 2008 and later you can define a primary key using an auto-generated UUID. To retrieve the UUID generated by the INSERT statement, add the OUTPUT option after your column definitions, and replace your statement.executeUpdate for statement.executeQuery and retrieve the value from the ResultSet. Here is a code fragment showing how to do it:
sqlStmt.append("INSERT INTO tableName");
sqlStmt.append(" (column1");
sqlStmt.append(", column2");
...
sqlStmt.append(" OUTPUT inserted.columnUUID");
sqlStmt.append(" VALUES (?, ?, ?, ?) ");
statement = connection.prepareStatement(sqlStmt.toString());
statement.clearParameters();
int index = 0;
ResultSet resultSet = statement.executeQuery();
if (resultSet.next())
{
result = resultSet.getString(1);
companyDB.varUUID = result;
}
Jop Eggan's answer solves it. However, you can do the following too in case the approach gives any errors:
String insertQuery = "INSERT INTO fixtures "
+ "(id, whatever1, whatever2, whatever3, whatever4, "
...
+ "created_at) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, "
+ "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
UUID id = UUID.randomUUID();
preparedStatement.setObject(1, id);

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server

I am having trouble with a java file when trying to run it on tomcat. I am suppose to be able to edit records that I put in a database, when I edit the records they do nothing. When I try to edit the records Tomcat throws me this error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'WHERE cus_id =
'13'' at line 1
I figure this is the code that has the error because it has all of the SQL commands. The delete function works. I just can not edit a record...
Thanks for the help!
package crud.data;
import java.sql.*;
import java.util.ArrayList;
import crud.business.Customer;
public class CustomerDB
{
//insert method (pass customer object to parameter customer)
public static int insert(Customer customer)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
//comment
String query
= "INSERT INTO customer (cus_fname, cus_lname, cus_street, cus_city,
cus_state, cus_zip, cus_phone, cus_email, cus_balance, cus_total_sales,
cus_notes) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, customer.getFname());
ps.setString(2, customer.getLname());
ps.setString(3, customer.getStreet());
ps.setString(4, customer.getCity());
ps.setString(5, customer.getState());
ps.setString(6, customer.getZip());
ps.setString(7, customer.getPhone());
ps.setString(8, customer.getEmail());
ps.setString(9, customer.getBalance());
ps.setString(10, customer.getTotalSales());
ps.setString(11, customer.getNotes());
return ps.executeUpdate();
} catch (SQLException e){
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
//update method
public static int update(Customer customer)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE customer SET "
+ "cus_fname = ?, "
+ "cus_lname = ?, "
+ "cus_street = ?, "
+ "cus_city = ?, "
+ "cus_state = ?, "
+ "cus_zip = ?, "
+ "cus_phone = ?, "
+ "cus_email = ?, "
+ "cus_balance = ?, "
+ "cus_total_sales = ?, "
+ "cus_notes = ?, "
+ "WHERE cus_id = ?";
try {
ps = connection.prepareStatement(query);
ps.setString(1, customer.getFname());
ps.setString(2, customer.getLname());
ps.setString(3, customer.getStreet());
ps.setString(4, customer.getCity());
ps.setString(5, customer.getState());
ps.setString(6, customer.getZip());
ps.setString(7, customer.getPhone());
ps.setString(8, customer.getEmail());
ps.setString(9, customer.getBalance());
ps.setString(10, customer.getTotalSales());
ps.setString(11, customer.getNotes());
ps.setString(12, customer.getId());
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
You have a comma , on the last value
+ "cus_notes = ?, "
so replace with
+ "cus_notes = ? "
Line 64 : remove the comma from + "cus_notes = ?, ".
It is syntax error as shown in your console log.
You have comma at the end of last value,remove it and give a try
"cus_notes = ?"
You should post more full of errors, it is easier to identify where mistakes, now according to your tip is SQL syntax errors.

How to solve com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dbo.Table2'

I am inserting data from Java in sql server 2008 DB by reading the data from 1st Database [WBSEDCL].[dbo].[Table1] and then inserting it into second Database [OrganizationMaster].[dbo].[Table2] .
I am using sqljdbc41.jar in my Project.
The code for insertion is as following -
private static Connection getNewDBConnection() {
System.out.println("************************Inside Get DB Connection**************************");
Properties props = new Properties();
if (connection != null)
try {
if (!connection.isClosed())
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
try {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://142.168.0.112:1733;DatabaseName=OrganizationMasterDB";
String user = "sa";
String password = "Dsdf#123";
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
if (!connection.isClosed())
System.out.println("---------------------DB Connection is Established----------------------");
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception Thrown ");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQL Exception Thrown");
e.printStackTrace();
}
return connection;
}
public static void insertDetailsList(PersonalLedger pl) {
Connection conn = getNewDBConnection();
PreparedStatement statement = null;
DetailsList dl = null;
int temp=0,shareAmount=0,shareBalance=0,theiftFundAmount=0,theiftFundInterest=0,GAmtDepo=0,GInterest=0,ShareWithdrawn=0;
String EmNo=null,MemberNo=null, fundString = "Share",status="Unknown",remarks="OtherAmount for Share is The Withdrawn Share Amount",sql=null;
boolean flag= false;
Date sdate = pl.SDate,gdate=pl.Gdate,tdate=pl.TDate;
EmNo = pl.EmNo;
MemberNo = pl.MemberNo;
shareAmount = pl.SAmtDepo;
shareBalance = pl.balance;
ShareWithdrawn = pl.ShareWithdrawn;
theiftFundAmount = pl.TAmtDepo;
theiftFundInterest = pl.TInterest;
GAmtDepo = pl.GAmtDepo;
GInterest = pl.GInterest;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try{
System.out.println("*****************INSERTING SHARE FUND DETAILS******************");
sql = "INSERT INTO [dbo].[DetailsList] VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
statement = conn.prepareStatement(sql);
statement.setString(1, pl.EmNo);
statement.setString(2, pl.MemberNo);
statement.setString(3,"Share");
statement.setLong(4, shareAmount);
/*Date share_date = (Date) formatter.parse(new Date());*/
statement.setLong(5,0);
statement.setLong(6,pl.ShareWithdrawn);
statement.setString(7,"Unknown");
statement.setString(8,"OtherAmount for Share is The Withdrawn Share Amount");
statement.setDate(9, pl.SDate);
statement.setDate(10,null);
statement.setLong(11, shareBalance);
temp = statement.executeUpdate();
if (temp != 0) {
flag = true;
System.out.println("ROW INSERTED SUCCESSFULLY");
}
} catch (Exception e) {
System.out.println("Exception in Insert Details List Items");
e.printStackTrace();
}
}
The problem whenever i run the code i get SQLException. The stackTrace is as below :
Exception in Insert Details List Items
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dbo.DetailsList'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:215)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5846)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1719)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:315)
at Test.insertDetailsList(Test.java:203)
at Test.main(Test.java:290)
I am completely dumbstruck by this error and could not find any relevant solution for the problem over the net !
Any help will be appreciated. Thanks.
EDIT: After doing some research I moved Table2 to the 1st Database, made necessary changes in connection string and executed the program. The code executed without any Error. So the question remains - 1.why the schema not found earlier when Table2 was under 2nd Database? 2.Is there any configuration required in the Database in order for java to connect with the correct schema and access the table, if so then What ?
Use the [dbname].[dbo].[tblname] query, e.g.select * from [dbname].[dbo].[tblname]
Assuming your INSERT is for Table2 then it should change from
sql = "INSERT INTO [dbo].[DetailsList] VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
to include the target database name. With something like (and you don't need the semi-colon in the query)
sql = "INSERT INTO [OrganizationMaster].[dbo].[DetailsList] VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
Check table DetailsList is exist and user has permission on this table, You can check this my logging into SQL server management studio from that user and try to access the table.

MySQL Query Through Java Syntax Error

I have this piece of code which inserts records into the accounts table:
String accNumber = jTextField5.getText();
String accName = jTextField4.getText();
String accAddress1 = jTextField3.getText();
String accAddress2 = jTextField2.getText();
String accCity = jTextField6.getText();
String accCounty = jTextField7.getText();
String accPostCode = jTextField9.getText();
String accContact = jTextField8.getText();
String query = "Insert into accounts (AccNo, name, address, address2, address3, City, County, PostCode, contact) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, accNumber);
connect.pst.setString(2, accName);
connect.pst.setString(3, accAddress1);
connect.pst.setString(4, accAddress2);
connect.pst.setString(5, null);
connect.pst.setString(6, accCity);
connect.pst.setString(7,accCounty);
connect.pst.setString(8, accPostCode);
connect.pst.setString(9, accContact);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This works just fine and inserts records into the accounts table. Next I have this piece of code which is meant to update the orderstable table which contains 6 fields; Order Number, AccNo, Incvoice Number, Description, Amount, VAT. The Order Number field has been set to auto increment
The code:
String accNumber = jTextField29.getText();
String invNo = jTextField20.getText();
String description = jTextField21.getText();
String vat = jTextField22.getText();
String amount = jTextField23.getText();
String query = "Insert into orderstable (Order Number, AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, "3");
connect.pst.setString(2, accNumber);
connect.pst.setString(3, invNo);
connect.pst.setString(4, description);
connect.pst.setString(5, amount);
connect.pst.setString(6, vat);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This code above returns a SQL syntax error. I am not sure why. What could the reason be for this SQL syntax error?
You can not have the column names with space and if you do so you need to have then in backticks
Insert into orderstable
(`Order Number`, AccNo, `Invoice Number`, Description, Amount, VAT)
Check here for more details http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
The auto increment field order number should not be include in the attribute section.
Your query should look like this
String query = "Insert into orderstable (AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?)";
order number column should not be include in field list, because it is auto increment

Categories