Inserting tuple into database - mysql

I am trying to check if a tuple is present. If it is then return the ID. If it is not present then insert it, create a new ID, and return that ID. This is what I have, however when I return the productID at the end, it is 0. I also keep getting the error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "7"Position: 360
Can anyone please help me understand where I am going wrong here? Thanks in advance
public int addProduct(String name, String manufacturer) throws SQLException{
int productId = 0;
connection.setAutoCommit(false);
Statement st = null;
st = this.connection.createStatement();
try {
int prod = 0;
Statement stmt = this.connection.createStatement();
stmt.execute("SELECT MAX(product_id) FROM Products");
ResultSet result = stmt.getResultSet();
if (result.next())
prod = result.getInt(1) + 1;
System.out.println(prod);
st.executeUpdate(
"DO " +
"$do$ " +
"BEGIN " +
"IF NOT EXISTS (SELECT 1 FROM Products WHERE " +
"Products.name = " + name + " AND " +
"Products.manufacturer = " + manufacturer + ") THEN " +
"INSERT INTO Products (product_id, name, category, manufacturer) " +
"VALUES (" + prod + ", " + name + ", " +
"" + null + ", " + manufacturer + "); " +
"END IF; " +
"END; " +
"$do$ ; "
);
ResultSet rsFind = st.executeQuery(
"SELECT Products.product_id FROM Products WHERE " +
"Products.name = '" + name + "' AND " +
"Products.manufacturer = '" + manufacturer + "; "
);
if (rsFind.next()) {
productId = rsFind.getInt("product_id");
System.out.println(productId);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (st != null) st.close();
}
this.connection.setAutoCommit(true);
return productId;
}

Related

c# How do I solve error mysql the used command is not allowed 1148?

I am executing a SQL query from C# but get the error:
MySql.Data.MySqlClient.MySqlException: 'The used command is not allowed with this MariaDB version'
Any help / pointers would be appreciated.
Here is my code:
private bool SaveCsvLines(string strFileName)
{
bool bResult = false;
if (ConnectToDatabase())
{
// Here we load the string variable with the SQL we want to run
string strLineInsert = "LOAD DATA LOCAL INFILE " +
"'" + strFileName + "' " +
"INTO TABLE pfetest1.maerskInvoiceLine " +
"FIELDS TERMINATED BY ',' " +
"LINES TERMINATED BY '\r\n' " +
"IGNORE 1 LINES " +
"(container, " +
"size, " +
"vessel, " +
"portOfLoad, " +
"porCityCode, " +
"portOfDischarge, " +
"podCityCode, " +
"postCode, " +
"invoiceNo, " +
"SET createdTimestamp = NOW(), " +
"createdUserId = 1, " +
"updatedTimestamp = NOW(), " +
"updatedUserId = 1, " +
"headerId = " + m_iFileId + ", " +
"eta = STR_TO_DATE(#eta, '%d/%m/%Y')";
//Now we execute that statement
MySqlCommand command = new MySqlCommand(strLineInsert, con);
bResult = (command.ExecuteNonQuery() == 1);
}
return bResult;
}
Switched to using MySQLBulkloader. That way I can define the columns etc. first then pump the data in.

Using Node.js to write MySQL One-to-Many relationship

I have tried doing this several ways, and maybe node.js is the wrong language to use for this purpose, but I thought it could be quickly done with it. I am taking a contacts table with names and addresses, and converting it to two tables with a one-to-many relationship, so that one contact can have multiple addresses. The desired data structure is like this:
Contact Table
contactId
firstName
lastName
phone
email
etc...
Address Table
addressId
contactId
street
city
state
etc...
Currently all fields are in the same table.
The result I am getting is that the data in the second query never changes. So if I write the contact query first, then it works as expected, but the addresses all end up as duplicates of one contact's address. If I insert the address record first, then I get duplicate records of one contact. I tried nesting the queries first, but I split them out when I got this behavior. My thinking was that I could write the queries . I need to write the contact and get the ID back, then write the address with the contactID. OR I need to write the address and get THAT ID back, and then write the contact, get that ID, and then do an update query to put the contactId into the address record. This last method is the attempt shown in the code below.
Here is my code currently:
var sql = "SELECT * FROM pfPeople";
connection.query(sql, function(err, result, fields) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var names = result[i].fullName.replace(/"/g, "'").split(" ");
var sql2 = "INSERT INTO contact (firstName, lastName, title, phone1, phone2, fax, email1, notes, org) VALUES (" +
"\"" + names[0] + "\", \"" + names[1] + "\", \"" + result[i].title.replace(/"/g, "'") + " \", \"" + result[i].phone1 + "\", \"" +
result[i].phone2 + "\", " + "\"" + result[i].phone3 + "\", \"" + result[i].email + "\", \"" + result[i].notes.replace(/"/g, "'") + "\", \"" +
result[i].org.replace(/"/g, "'") + "\")";
var street = result[i].street;
var city = result[i].city;
var state = result[i].state;
var zip = result[i].zip;
var country = result[i].country;
var sql3 = "INSERT INTO address (address1, city, state, zip, country) VALUES (" +
"\"" + street + "\", \" " + city + "\", \"" + state + "\", \"" + zip + "\", \"" + country + "\")";
var contactId;
var addressId;
connection.query(sql2, function(err, cResult) {
if (err) throw err;
var contactId = cResult.insertId;
console.log("Inserted ID: " + contactId);
});
connection.query(sql3, function(err, aResult) {
if (err) throw err;
var addressId = aResult.insertId;
});
var sql4 = "UPDATE address set contactId = " + contactId + " WHERE (addressId = " + addressId + ")";
connection.query(sql4, function(err, uRes) {
console.log("Address updated " + addressId + " " + contactId);
});
if (i > 3) break;
}
});
well i add some promises to make it easier. the problem was you didnt wait for the responses to finish. try this code
var sql = "SELECT * FROM pfPeople";
connection.query(sql, function(err, result, fields) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var names = result[i].fullName.replace(/"/g, "'").split(" ");
var sql2 = "INSERT INTO contact (firstName, lastName, title, phone1, phone2, fax, email1, notes, org) VALUES (" +
"\"" + names[0] + "\", \"" + names[1] + "\", \"" + result[i].title.replace(/"/g, "'") + " \", \"" + result[i].phone1 + "\", \"" +
result[i].phone2 + "\", " + "\"" + result[i].phone3 + "\", \"" + result[i].email + "\", \"" + result[i].notes.replace(/"/g, "'") + "\", \"" +
result[i].org.replace(/"/g, "'") + "\")";
var street = result[i].street;
var city = result[i].city;
var state = result[i].state;
var zip = result[i].zip;
var country = result[i].country;
var sql3 = "INSERT INTO address (address1, city, state, zip, country) VALUES (" +
"\"" + street + "\", \" " + city + "\", \"" + state + "\", \"" + zip + "\", \"" + country + "\")";
const contacPromise = new Promise((resolve,reject) =>{
connection.query(sql2, function(err, cResult) {
if (err) return reject( err);
resolve( cResult.insertId);
});
})
const addressPromise = new Promise((resolve,reject) =>{
connection.query(sql3, function(err, aResult) {
if (err) return reject( err);
resolve(aResult.insertId);
});
})
Pomise.all([contacPromise,addressPromise])
.then(([contactId,addressId]) =>{
var sql4 = "UPDATE address set contactId = " + contactId + " WHERE (addressId = " + addressId + ")";
connection.query(sql4, function(err, uRes) {
console.log("Address updated " + addressId + " " + contactId);
});
})
.catch(err => throw err)
if (i > 3) break;
}
});

getting fatal errors when work with lots of data

Below i have attach my code. in my code it stops on the line :
cmdUpdate.executenonquery();
and after few seconds exception is generated and the catch block is executed.in catch block it says
fatal error
I dont know why this error occurs.
And one main important thing is firstly i have executed this code without any LIMIT condition in the query specified in cmdPayment command.then it does not generate any exception.
But when i remove LIMIT condition from query then it generates exception.
This query will select data from table which has around 20.
int freeMonths=0;
string subscriptionTxnId = null;
string paymentType=null;
string subscriptionDate = null;
string userid = null;
string date = "2014-02-01 00:00:00";
using (MySqlConnection connPayment = new MySqlConnection(connString))
{
connPayment.Open();
freeMonths = 0;
MySqlCommand cmdPayment = new MySqlCommand("SELECT userid,subscr_txn_id,DATE_FORMAT(subscr_date,'%Y-%m-%d %k:%i:%s'),payment_type from payment limit 10000",connPayment);
MySqlDataReader readerPayment;
readerPayment = cmdPayment.ExecuteReader();
while (readerPayment.Read())
{
try
{
freeMonths = 0;
if (readerPayment.GetValue(0) != DBNull.Value && readerPayment.GetValue(1) != DBNull.Value && readerPayment.GetValue(2) != DBNull.Value && readerPayment.GetValue(3) != DBNull.Value)
{
userid = readerPayment.GetString(0);
subscriptionTxnId = readerPayment.GetString(1);
subscriptionDate = readerPayment.GetString(2);
paymentType = readerPayment.GetString(3);
using (MySqlConnection connPaymentDetails = new MySqlConnection(connString))
{
connPaymentDetails.Open();
MySqlCommand cmdPaymentDetails = new MySqlCommand("select free_months from payment_details where userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' AND payment_date = '" + subscriptionDate + "' ", connPaymentDetails);
MySqlDataReader readerPaymentDetails = cmdPaymentDetails.ExecuteReader();
if (readerPaymentDetails.HasRows)
{
readerPaymentDetails.Read();
freeMonths = readerPaymentDetails.GetInt32(0);
}
}
string query = null;
MySqlConnection conUpdate = new MySqlConnection(connString);
if (paymentType == "annual" || paymentType == "Annual")
{
//MySqlCommand cmd001 = new MySqlCommand("")
query = "update payment set end_date = (select DATE_ADD(DATE_ADD('" + subscriptionDate + "' ,INTERVAL 1 YEAR),INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
else if (paymentType == "quarter" || paymentType == "Quarter" || paymentType == "Quarterly")
{
freeMonths += 3;
query = "update payment set end_date = (select DATE_ADD('" + subscriptionDate + "', INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
else if (paymentType == "month" || paymentType == "Month" || paymentType == "Monthly")
{
freeMonths += 1;
query = "update payment set end_date = (select DATE_ADD('" + subscriptionDate + "', INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
MySqlCommand cmdUpdate = new MySqlCommand(query, conUpdate);
conUpdate.Open();
cmdUpdate.ExecuteNonQuery();
int num = 0;
if (num == 0)
{
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

update query and calculation part in GRN

String status = "active", nit = "", grniid = "", sumn = "";
try {
Connection ss = Class_DB.myconnection();
Statement st = ss.createStatement();
ResultSet rs = st.executeQuery("select stock_in_hand from item_supplier where item_ID =('" + TF_GRN_ITEMID.getSelectedItem() + "')");
grniid = TF_GRN_NO_OF_ITEM.getText();
int aa = Integer.parseInt(grniid);
while (rs.next()) {
nit = rs.getString("stock_in_hand");
}
int bb = Integer.parseInt(nit);
sumn = grniid + nit;
int cc = Integer.parseInt(sumn);
st.executeUpdate("insert into grn1 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_SUPPLIERID.getSelectedItem() + "','" + TF_GRN_AMOUNT.getText() + "','" + TF_GRN_DATE.getText() + "')");
st.executeUpdate("insert into grn2 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_ITEMID.getSelectedItem() + "','" + TF_GRN_EXP_DATE.getText() + "','" + TF_GRN_TAX.getText() + "','" + TF_GRN_NO_OF_ITEM.getText() + "','" + TF_GRN_GAMOUNT.getText() + "','" + TF_GRN_NAMOUNT.getText() + "','" + TF_GRN_QTY.getText() + "','" + TF_GRN_UNIT.getText() + "','" + TF_GRN_FREE.getText() + "','" + TF_GRN_DIS.getText() + "')");
st.executeUpdate("update item_supplier set stock_in_hand='" + cc + "' where item_ID='" + TF_GRN_ITEMID.getSelectedItem() + "'");
JOptionPane.showMessageDialog(null, "Data Saved");
clearing();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "There is some error.Please contact admin");
ex.printStackTrace();
}
This is the GRN Query. GRN stands for Good Receive Note.
When we recieve Goods/Items from the supplier the company receives a GRN.
The Details of the items will be included in the GRN.
These data/details will be inserted in GRN1 table, GRN2 table and item_Supplier table will be updated according to it.
nit is the variable, using item_id table and item supplier table, stock in hand will be retrieved.
bb is the variable used to pass nit to an integer.
grnid is No of items which we type in the interface will be included in grnidvariable.
aa is the variable used to pass grnid to integer.
class_DB - connection class of the database.
Our problem is
1) he is inserted to GRN1 and GRN2 tables, but item_supplier table is not updated.
2) We want to know if our calculation is correct or not.

DataAdapter.Update() doesn't work to update

my sql statments are as follows
the insert statement only works
update and delete statements don't work
Purchase_InvoiceNo is a primary key column of Purchase table
i get this value like this and insert its value to PurchaseProduct table
"SELECT IDENT_CURRENT ('Purchase') AS [Purchase_InvoiceNo]"
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct " +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
string updatcmd_PurchaseProduct =
"UPDATE PurchaseProduct "
+ " SET "
+ " PurchaseProduct_SerialNo =#PurchaseProduct_SerialNo"
+ ", Purchase_InvoiceNo =#Purchase_InvoiceNo"
+ ", ProductNo =#ProductNo"
+ " PurchaseProduct_Quantity =#PurchaseProduct_Quantity "
+ ", PurchaseProduct_Unit =#PurchaseProduct_Unit"
+ ", PurchaseProduct_Price =#PurchaseProduct_Price"
+ " Where "
+ " PurchaseProduct_No=#PurchaseProduct_No";
string insertcmd_PurchaseProduct = "INSERT INTO PurchaseProduct" +
"(" +
" PurchaseProduct_SerialNo"+
",Purchase_InvoiceNo" +
",ProductNo" +
",PurchaseProduct_Quantity " +
",PurchaseProduct_Price" +
",PurchaseProduct_Unit" + //6
")" +
"Values" +
"(" +
" #PurchaseProduct_SerialNo"+
",#Purchase_InvoiceNo" +
",#ProductNo " +
",#PurchaseProduct_Quantity " +
",#PurchaseProduct_Price" +
",#PurchaseProduct_Unit" + //6
");";
Your Delete command appears to be incomplete:
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct " +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
should be:
string deletecmd_PurchaseProduct =
#"DELETE FROM PurchaseProduct WHERE" +
"PurchaseProduct_No=#PurchaseProduct_No and "+
"Purchase_InvoiceNo=#Purchase_InvoiceNo ";
I can't see why the INSERT should fail unless you're inserting a duplicate primary key value or you're not inserting data into a non-nullable field which does not have a default.
string updatcmd_PurchaseProduct =
"UPDATE PurchaseProduct "
+ "SET PurchaseProduct_SerialNo = #PurchaseProduct_SerialNo, "
+ "Purchase_InvoiceNo = #Purchase_InvoiceNo, "
+ "ProductNo = #ProductNo, "
+ "PurchaseProduct_Quantity = #PurchaseProduct_Quantity, "
+ "PurchaseProduct_Unit = #PurchaseProduct_Unit, "
+ "PurchaseProduct_Price = #PurchaseProduct_Price "
+ "Where PurchaseProduct_No = #PurchaseProduct_No";
There was a missing comma above.