I am getting an error in my code from an sql statement that works fine in the query design in MS Access - sql

The SQL statement runs properly in the query design in MS Access but I get the following error in the netbeans code:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 4.
I don't know what this error message means by too few parameters so I do not know how to fix it.
Any help on why my code is not working will be grateful.
This class imports two tables from a database as one SQL statement into two arrays.
public class GuestArray
{
private Guest[] guest = new Guest[100];
private Reservations[] res = new Reservations[100];
private int size =0;
Connect conn = new Connect("GuestInfo.mdb");
public GuestArray()
{
String sql = "SELECT GuestID, Title,Name,Surname,CountryLivingIn,"
+ "contactNumber,emailAddress,Day(checkInDate)AS idd, MONTH(checkInDate) AS imm,"
+ " YEAR(checkInDate) AS iYY, Day(checkOutDate)AS odd, MONTH(checkOutDate) AS omm, "
+ "YEAR(checkOutDate) AS oYY,RoomType,Adults,Children,Requests FROM ReservationDetails,"
+ "GuestDetails WHERE GuestDetails.GuestID=ReservationDetails.ReservationID";
try
{
ResultSet rs = conn.query(sql);
while(rs.next())
{
int id = rs.getInt("GuestID");
String t = rs.getString("Title");
String n = rs.getString("Name");
String s = rs.getString("Surname");
String c = rs.getString("CountryLivingIn");
String num = rs.getString("contactNumber");
String e = rs.getString("emailAddress");
guest[size] = new Guest(id,t,n,s,c,num,e);
int cid = rs.getInt("idd");//check-in-day
int cim = rs.getInt("imm");//check-in-month
int ciy = rs.getInt("iyy");//check-in-year
int cod = rs.getInt("odd");//check-out-day
int com = rs.getInt("omm");//check-out-month
int coy = rs.getInt("oyy");//check-out-year
String rt = rs.getString("RoomType");
int ad = rs.getInt("Adults");
int ch = rs.getInt("Children");
String req = rs.getString("Requests");
res[size] = new Reservations(id,t,n,s,c,num,e,cid,cim,ciy,cod,com,coy,rt,ad,ch,req);
size++;
}
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}

Related

Cannot add row without complete selection of batch/serial numbers

ERROR: (-4014) Cannot add row without complete selection of batch/serial numbers.
The default function of DI API SaveDraftToDocument() is working fine on MS SQL Database but not SAP HANA.
I am posting the Delivery document with Serial Numbers.
SAPbobsCOM.Documents oDrafts;
oDrafts = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
oDrafts.GetByKey(Convert.ToInt32(EditText27.Value));
var count = oDrafts.Lines.Count;
var linenum = oDrafts.Lines.LineNum;
//Validation
#region
var RsRecordCount = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQryRecordCount = String.Format("Select * from \"SANTEXDBADDON\".\"#TEMPITEMDETAILS\" where \"U_DraftNo\" = '{0}'", EditText27.Value);
RsRecordCount.DoQuery(sQryRecordCount);
#endregion
if (count == RsRecordCount.RecordCount)
{
//LINES
string ItemCode = "", WhsCode = ""; double Quantity = 0; int index = 0;
for (int i = 0; i < oDrafts.Lines.Count; i++)
{
oDrafts.Lines.SetCurrentLine(index);
ItemCode = oDrafts.Lines.ItemCode;
//SERIAL NUMBERS
var RsSerial = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
string table = "\"#TEMPSERIALS\"";
var sQrySerial = String.Format(
"Select \"U_ItemCode\" , \"U_DistNumber\" from \"SANTEXDBADDON\".\"#TEMPSERIALS\" where " +
"\"U_DraftNo\" = '{0}' and \"U_ItemCode\" = '{1}'", EditText27.Value, ItemCode);
RsSerial.DoQuery(sQrySerial);
int serialindex = 1, lineindex = 0;
#region
if (RsSerial.RecordCount > 0)
{
while (!RsSerial.EoF)
{
//OSRN SERIALS
var RsSerialOSRN = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQrySerialOSRN = String.Format(
"Select * from OSRN where \"DistNumber\" = '{0}' and \"ItemCode\" = '{1}'"
, RsSerial.Fields.Item("U_DistNumber").Value.ToString(), ItemCode);
RsSerialOSRN.DoQuery(sQrySerialOSRN);
oDrafts.Lines.SerialNumbers.SetCurrentLine(0);
oDrafts.Lines.SerialNumbers.BaseLineNumber = oDrafts.Lines.LineNum;
oDrafts.Lines.SerialNumbers.SystemSerialNumber =
Convert.ToInt32(RsSerialOSRN.Fields.Item("SysNumber").Value.ToString());
oDrafts.Lines.SerialNumbers.ManufacturerSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.InternalSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.Quantity = 1;
if (RsSerial.RecordCount != serialindex)
{
Application.SBO_Application.StatusBar.SetText("INTERNAL NO " + oDrafts.Lines.SerialNumbers.InternalSerialNumber, SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
oDrafts.Lines.SerialNumbers.Add();
serialindex++;
lineindex++;
}
RsSerial.MoveNext();
}
}
#endregion
index++;
}
var status = oDrafts.SaveDraftToDocument();
if (status == 0)
{
oDrafts.Remove();
Application.SBO_Application.StatusBar.SetText("Delivery Posted Successfully !", SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
}
else
{
int code = 0; string message = "";
oCompany.GetLastError(out code, out message);
Application.SBO_Application.SetStatusBarMessage(message, SAPbouiCOM.BoMessageTime.bmt_Medium, true);
}
}`
The error you have posted explains the problem. You are trying to deliver products but have not included all of the serial/batch numbers.
I don't think there's enough information to be sure where this problem happens, but here are some pointers:
You are reading the serial numbers from a custom table. Are the values you are reading valid? For example, could another user have added them to a different order? Could the values be for a different product?
Are you specifying the correct quantity of serial numbers? Is it possible that the item quantity on the line is more than the number of serial numbers you are adding?
Believe the error message until you can prove it's wrong. It doesn't seem like this is a HANA issue (we use HANA extensively) it's a logical problem with the data you are providing.
You may want to capture more debugging information to help you if you can't easily identify where the problem is.

ODBC-2028 Error SAP B1

I am trying to add a purchase order by DI API for SAP B1. My code is working on my client but I tried it as an addon on another company that has different data. And it gives the error: "No matching records found(ODBC-2028)". Here is a part of my code:
public void createPOrderFor(int id,
string itemCode,
string itemName,
int qty,
int satisSip,
string cardCode,
string cardName,
string releaseDate)
{
SAPbobsCOM.Documents BO_item;
BO_item = (SAPbobsCOM.Documents)getCompany().GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseOrders);
base.doConnectionInfo();
server = base.server;
database = base.database;
user = base.user;
pass = base.pass;
string year = releaseDate.Substring(0, 4);
string month = releaseDate.Substring(4, 2);
string day = releaseDate.Substring(6, 2);
releaseDate = year + "-" + month + "-" + day;
BO_item.Lines.ItemCode = itemCode;
BO_item.Lines.ItemDescription = itemName;
BO_item.Lines.Quantity = qty;
BO_item.Lines.ShipDate = DateTime.Parse(releaseDate);
BO_item.Lines.UserFields.Fields.Item("U_SatisSip").Value = satisSip;
BO_item.Lines.Add();
BO_item.Comments = satisSip + " numaralı satış siparişine istinaden";
BO_item.CardCode = cardCode;
BO_item.CardName = cardName;
BO_item.NumAtCard = "";
BO_item.Series = 13;//birincil
//BO_item.Segment -- it is read only.
BO_item.TaxDate = DateTime.Now;
BO_item.DocDate = DateTime.Now;
BO_item.DocDueDate = DateTime.Parse(releaseDate);
BO_item.SalesPersonCode = 4;//default Hakan Yılmaz
BO_item.DocumentsOwner = 4;
BO_item.DiscountPercent = 0.0;
BO_item.Address2 = "TURKEY";
BO_item.Address = "";
BO_item.TransportationCode = 1;
BO_item.AgentCode = null;
BO_item.JournalMemo = "Satınalma siparişleri - " + cardCode;
BO_item.GroupNumber = 1;//net30
BO_item.PaymentMethod = null;
BO_item.Project = null;
BO_item.UserFields.Fields.Item("U_SatSip").Value = satisSip;
var retVal = BO_item.Add();
int errorCode = 0;
string errMsg = "";
if (retVal != 0)
{
getCompany().GetLastError(out errorCode, out errMsg);
SAPbouiCOM.Framework.Application.SBO_Application.StatusBar.SetText("Error: " + errMsg , SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
}
First of all remove all null fields. If there are DI Object fields that you cannot provide a value for, you should not set them equal to null.
BO_item.AgentCode = null;
BO_item.PaymentMethod = null;
BO_item.Project = null;
Just remove them completely. Also instead of Date.Time.Now try setting a date in this format: 20180531 for all date fields as a test.
BO_item.DocDate = "20180531"
If it returns the same error, attempt to test this in an SAP Business One Demo Database (can be obtained from sap partneredge).
Also, Ensure the User Defined Fields you are trying to set values for exist in your new customer's database
let me know how it works for you so we can continue.

SQL Exception: Table does not exist when accessed using SOAP service

I am using Derby database in embedded mode. I have written a CreateDB class with main() function that creates/inserts/select in a table. Works fine.(I have necessary jar files in project build path:) )
But, when i use same database and table to select rows in my Soap webservice, it gives me error that table doesn't exist. here is the code:
For CreateDB (Works Perfectly fine)
package com.myShop.www.ShipmentService;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDB {
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:Shipment_DB;create=true";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL);
String SQLString = "CREATE TABLE SHPMTTYPAV_TBL1(" +
"SHPMTID INT NOT NULL, " +
"NAME VARCHAR(30) NOT NULL, " +
"DESCR VARCHAR(45) NOT NULL, " +
"MINCOST DOUBLE NOT NULL, " +
"COSTPEROUNCE DOUBLE NOT NULL, " +
"ESTDLVYDAYS INT NOT NULL, " +
"PRIMARY KEY(SHPMTID))";
connection.createStatement().execute((SQLString));
String insertSQL = "INSERT INTO SHPMTTYPAV_TBL1 VALUES(5, 'Priority Mail', 'Any item can be shipped', 5, .02, 1)";
connection.createStatement().execute(insertSQL);
// invoke sql query
String selectSQL = "SELECT * From SHPMTTYPAV_TBL1";
Statement prepStmt = connection.createStatement();
ResultSet rs = prepStmt.executeQuery(selectSQL);
while (rs.next()){
System.out.println(rs.getInt("SHPMTID") + rs.getString("NAME") + rs.getString("DESCR") + rs.getDouble("MINCOST") + " " + rs.getDouble("COSTPEROUNCE"));
}
}
}
Code in SOAP service Implementation class: - Error of Table not found
public class ShipmentServiceBindingImpl implements ShipmentServicePortType{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:Shipment_DB;create=true";
public com.myShop.www.ShipmentService.ItemsInOrderResponseType[] getShpmtTps_Csts_DlvyDts(com.myShop.www.ShipmentService.ItemsInOrderType[] itemsInOrder) throws java.rmi.RemoteException, ClassNotFoundException, SQLException {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL);
String selectSQL = "SELECT * From SHPMTTYPAV_TBL1";
Statement prepStmt = connection.createStatement();
ResultSet rs = prepStmt.executeQuery(selectSQL);
int len = itemsInOrder.length;
ItemsInOrderResponseType[] res = new ItemsInOrderResponseType[len];
for(int i = 0; i < len; i++){
rs.next();
res[i] = new ItemsInOrderResponseType();
res[i].setShpmtID(rs.getInt("SHPMTID"));
res[i].setShpmtName(rs.getString("NAME"));
res[i].setCost(rs.getDouble("COSTPEROUNCE"));
res[i].setEstDlvyDays(rs.getDouble("MINCOST"));
}
if (rs != null) rs.close();
if (prepStmt != null) prepStmt.close();
if (connection != null) connection.close();
return res;
}
}
Try setting derby.system.home to the same value in both cases. If unset Derby uses the current directory which is likely different in the two cases.

MS Access [Microsoft][ODBC Driver Manager] Invalid cursor state

I had the error in this code snippet:
private String[][] connectToDB(String query) throws ClassNotFoundException{
String[][] results = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:/EACA_AgroVentures1.accdb";
conn = DriverManager.getConnection(db);
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsm = rs.getMetaData();
rs.beforeFirst();
int columns = rsm.getColumnCount();
int rows = getRowCount(rs);
//int rows = rs.getFetchSize();
int rowCount = 0;
results = new String[rows][columns];
//System.out.println(rows+" "+columns);
while((rs!=null) && (rs.next())){
for(int i = 1; i < columns; i++){
results[rowCount][i-1] = rs.getString(i); // --> ERROR SHOWS HERE
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
rowCount++;
}
rs.getStatement().close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
return results;
}
My query consists of the following:
private void loadMR(){
try {
String query = "SELECT dealerCode, SUM(kg) AS totalKG, SUM(price) AS totalPrice, returnDate, BID FROM meatReturns GROUP BY BID, dealerCode, returnDate;";
Object[][] result = connectToDB(query);
// some more code below..
I tried using the first code with some other query given in another method:
private void loadDealers(){
try {
String query = "SELECT * FROM Dealers";
Object[][] result = connectToDBWithRows(
query);
// some more code..
and it runs perfectly well. What is going on here? How can i fix this problem?
UPDATE: the only difference of connectToDBWithRows and connectToDB is the while loop that manages the resultSet
// Snippet from connectToDBWithRows()
while((rs!=null) && (rs.next())){
for(int i = 0; i < columns; i++){
if (i == 0){
// Do nothing
}else{
results[rowCount][i] = rs.getString(i);
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
}
rowCount++;
}
and this is my getRowCount() method
private int getRowCount(ResultSet resultSet){
int size = 0;
try {
resultSet.last();
size = resultSet.getRow();
resultSet.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return size;
}
I've noticed that sometimes, Access needs you to specify the table name when referring to columns in sql statements. Try the following:
private void loadMR(){
try {
String query = "SELECT meatReturns.dealerCode, SUM(meatReturns.kg) AS totalKG, SUM(meatReturns.price) AS totalPrice, meatReturns.returnDate, meatReturns.BID FROM meatReturns GROUP BY meatReturns.BID, meatReturns.dealerCode, meatReturns.returnDate";
Object[][] result = connectToDBWithRows(query);

Topic views do not show up in jTable

I try to code a forum using java swing. Firstly, on click for the jTable, it will lead to eForumContent.class which pass in the id together.
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int id = 0;
eForumTopics topics = new eForumTopics(id);
topics.retrieveDiscussion();
eForumThreadContent myWindow = new eForumThreadContent(id);
myWindow.getJFrame().setVisible(true);
}
});
I initialize the id first. But I set my id in database table to auto number. Then I call the retrieveDiscussion method to get the id from database and pass it to eForumThreadContent. Here are my codes for retrieveDiscussion method.
public boolean retrieveDiscussion(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String dbQuery = "SELECT * FROM forumTopics WHERE topic_id = '" + id
+ "'";
rs = db.readRequest(dbQuery);
db.terminate();
return success;
}
}
Then, inside the eForumThreadContent, I want to display the content of chosen thread using a table. So I use the id which I pass in just now and insert into my sql statement. Here are my codes.
public eForumThreadContent(int id) {
this.id = id;
}
if (jTable == null) {
Vector columnNames = new Vector(); // Vector class allows dynamic
// array of objects
Vector data = new Vector();
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = '"+id+"'";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(400); // second column is bigger
}else {
column.setPreferredWidth(200);
}
}
String header[] = { "Title", "Description", "Posted by" };
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel()
.getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.getTableHeader().setFont( new Font( "Dialog" , Font.PLAIN, 20 ));
jTable.getTableHeader().setForeground(Color.white);
jTable.getTableHeader().setBackground(new Color(102, 102, 102));
jTable.setEnabled(false);
jTable.setRowHeight(100);
jTable.getRowHeight();
jTable.setFont( new Font( "Dialog" , Font.PLAIN, 18 ));
}
return jTable;
}
However, the table inside eForumThreadContent is empty even when I clicked on certain thread. It also gives me an error message.
[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at DBController.database.DBController.readRequest(DBController.java:27)
at kioskeForum.entity.eForumTopics.retrieveDiscussion(eForumTopics.java:67)
at kioskeForum.ui.eForumDiscussion$3.mouseClicked(eForumDiscussion.java:296)
I research online to get an idea for topic views using id. But my table does not show up anything. Can somebody enlighten me how to fix it? Or any other ways to display topic views in java swing? Thanks in advance.