Multi tables update using javafx and Mysql - mysql

I have to update a customer information that are spread over 4 Mysql tables. I created 1 Customer class. when I first add the information it is added to an observable list that populate a table, and by clicking on a selected row the information are displayed in textboxes to edit, but the updates are not being saved into the MySQL tables. Can you tell if it is from this part of code or is it coming from somewhere else in the program. What is wrong with my code ?
public void updateCustomer(Customer selectedCustomer, String user, LocalDateTime timePoint) throws Exception{
String query = "UPDATE customer, address, city, country"
+ " SET customer.customerName = '"+selectedCustomer.getCustomerName()+"', customer.lastUpdate = '" +timePoint+"', customer.lastUpdateBy = '"+user+ "', "
+ " address.address = '" +selectedCustomer.getAddress()+ "', address.address2 = '" +selectedCustomer.getAddress2()+ "', address.postalCode = '" +selectedCustomer.getPostalCode()+ "', address.phone = '" +selectedCustomer.getPhone()+ "', address.lastUpdate='" +timePoint+ "', address.lastUpdateBy = '" +user+ "', "
+ " city.city = '"+selectedCustomer.getCity()+"',city.lastUpdate='"+timePoint+"',city.lastUpdateBy = '"+user+ "', "
+ " country.country = '"+selectedCustomer.getCountry()+"',country.lastUpdate ='"+timePoint+"',country.lastUpdateBy = '"+user+ "' "
+ " WHERE customer.customerId = " +selectedCustomer.getCustomerId()+ " AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId " ;
statement.executeUpdate(query);
}

What I usually do is:
Create my data class.
Create load and save methods on my DB class.
Set up the FXML so that the TableColumns show the right information from the data class
Get the data into an ObservableList from the database (I like to use Derby but that shouldn't make a difference) and put that into the table.
Add a listener to the selection model so that when the selected item in the table changes, the selected item is referenced by another variable (say "selectedCustomer" and that variable's data is shown into the editable textfields or comboboxes or whatever. Note that I don't use bindings when showing the selectedCustomer in the textboxes. I just use plain setTexts.
When the user clicks on Save or something, the data in the textfields are set into the selectedCustomer (for example, selectedCustomer.setName(nameText.getText());)
I call the database class' save method (for example, DB.save(selectedCustomer); )
That should do the trick! Never failed me yet.
However, I may be at fault here, since I couldn't be bothered to read your SQL statement. Please, for goodness sake, learn to use PreparedStatements! First, I don't really understand how your table is set up, so I can't really comment, but it's really hard to understand. However, if I were to take a wild guess, I think the problem may have something to do with this part here:
WHERE ... AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId
I don't understand how that part works--either that SQL statement does not make sense or my SQL needs practice (probably the latter).
Since you use MySQL, how about you use a manager (such as PHPMyAdmin or since you are using Java, SQuirreL) to try executing your SQL statement manually and see what happens? If you enter the SQL statement and nothing changed (when there should be) then your SQL statement is at fault.

Related

Wildcard in textbox

I have two tables.
1.Test_Cap_Model1
2.Router
I have one report: ReportYield
In this report I made one control text box that contains code sql statement as below
This code will generate route value from router table if model value in report (its from query that generate from test_cap_model1 table) contain in router.[testmodel].
I tried to do in query but my problem is value of model in test_cap_model1 table are not the same in test model in router table. As example
Model value in test_cap table = 1471D3BTL-Non HW
but
Test Model Value in Router table = 1471D3BTL
Use DLookup for such tasks, and the Value property:
Private Sub Text10_Click()
Me!Text10.Value = DLookup("[Route]", "[Router]", "[Model] Like '" & Me!Model.Value & "*'")
' or:
' Me!Text10.Value = DLookup("[Route]", "[Router]", "[Model] Like '" & Me!Model.Value & "%'")
End Sub
There is nothing to requery. And do change your control names to something meaningful.

Spark ETL job execute mysql only once

I have an ETL job in Spark that also connects to MySQL in order to grab some data. Historically, I've been doing it as follows:
hiveContext.read().jdbc(
dbProperties.getProperty("myDbInfo"),
"(SELECT id, name FROM users) r",
new Properties()).registerTempTable("tmp_users");
Row[] res = hiveContext.sql("SELECT "
+ " u.name, "
+ " SUM(s.revenue) AS revenue "
+ "FROM "
+ " stats s "
+ " INNER JOIN tmp_users u "
+ " ON u.id = s.user_id
+ "GROUP BY "
+ " u.name "
+ "ORDER BY "
+ " revenue DESC
+ "LIMIT 10").collect();
String ids = "";
// now grab me some info for users that are in tmp_user_stats
for (i = 0; i < res.length; i++) {
s += (!s.equals("") ? "," : "") + res[i](0);
}
hiveContext.jdbc(
dbProperties.getProperty("myDbInfo"),
"(SELECT name, surname, home_address FROM users WHERE id IN ("+ids+")) r",
new Properties()).registerTempTable("tmp_users_prises");
However, when scaling this to multiple worker nodes, whenever I use the tmp_users table, it runs the query and it gets executed (at least) once per node, which boils down to our db admin running around offices with a knife.
What's the best way to handle this? Can I run the job on like 3 machines, limiting it to 3 queries and then write the data to Hadoop for other nodes to use it or what?
Essentially - as suggested in comments - I could run a query outside of the ETL job which can prepare data from MySQL side and import it to Hadoop. However, there could be subsequent queries, which suggest a solution more in line with Spark and JDBC connection setup.
I'll accept the Sqoop solution as it at least give a more streamlined solution, although I'm still not yet sure it will do the job. If I find something, I'll edit the question again.
You can cache data:
val initialDF = hiveContext.read().jdbc(
dbProperties.getProperty("myDbInfo"),
"(SELECT id, name FROM users) r",
new Properties())
initialDF.cache();
initialDF.registerTempTable("tmp_users");
After first read, data will be cached in memory
Alternative (that doesn't hurt DBA ;) ) is to use Sqoop with parameter --num-mappers=3 and then import result file to Spark

Error 3075: Syntax missing operator

After many trial and errors run, I cannot seem to fix the syntax error. I am trying to concatenate some data and have been using Allen Browne (where you can find the code for ConcatRelated) and I got the SQL from another stackoverflow question but they had different data types.
The following is the SQL for the query that I am trying to run, which is surprisingly producing the correct results as well as this error which makes the query useless. (StmntNd is Text field and Assmt_Group is a Number field)
SELECT sub.[StmntNd], sub.[Assmt_Group], sub.[StmntDes], ConcatRelated("Num_Code", "tbl_Property", "[StmntNd] = '" & sub.[StmntNd] & "' AND [Assmt_Group] = " & sub.[Assmt_Group], "num_Code") AS concat_num_code
FROM (SELECT q.[StmntNd], q.[Assmt_Group], q.[StmntDes] FROM tbl_Property AS q GROUP BY q.[StmntNd], q.[Assmt_Group], q.[StmntDes]) AS sub
ORDER BY sub.StmntNd, sub.Assmt_Group;
This is the error that I am currently receiving:
Thank you very much for any help. No matter what combination of quotes and apostrophes I use, I seem to keep getting an error.
try this
SELECT sub.[StmntNd], sub.[Assmt_Group], sub.[StmntDes], ConcatRelated("Num_Code", "tbl_Property", "[StmntNd] = '" & sub.[StmntNd] & "' AND [Assmt_Group] = " & sub.[Assmt_Group], "num_Code") AS concat_num_code
FROM (SELECT q.[StmntNd], q.[Assmt_Group], q.[StmntDes] FROM tbl_Property AS q
GROUP BY q.[StmntNd], q.[Assmt_Group], q.[StmntDes]) AS sub
Where q.[StmntNd] is Not Null
ORDER BY sub.StmntNd, sub.Assmt_Group;
Add where clause to the Column, I assumed column as q.[StmntNd]

MySQL Statement error in JSP

I have an issue with an sql statement and i dont know how to handle it. Here is the problem:
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")')";
The values are obtained from the post form which contains free text. The problem is, whenever a user enters characters like ', i will get an error because that tells the compiler that the value is over here(i suppose) and now look for the next value. I don't know how to include these characters and send them to database without having an error. Any help would be appreciated. Thank you.
The character ' is used to surround literals in MySQL. And if any data contains such character as part of it, we have to escape it. This can be done using Prepared Statement in Java.
Change your query code accordingly.
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`)
VALUES ( ?, ?,? )";
Now define a PreparedStatement instance and use it to bind values.
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, session.getAttribute("id") );
pst.setString( 2, request.getParameter("RunningProjects") );
pst.setString( 3, request.getParameter("MainOrders") );
int result = pst.executeUpdate();
And, I suggest use of beans to handle business logic.
change
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")
+ "')";
I think you are using normal statement in your JDBC code. Instead, I would suggest you to use Prepared statement. Prepared statement is generally used to eliminate this kind of problem and caching issue. If you will use prepared statement I think your problem will be solved

how to change the date format as it not the same with the database

As the coding show at textbox 18/02/2012 (for example). but in database it is 02/18/2012.
TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy")
cboTermCode.Focus()
Calendar.Visible = False
But when i want to retrieve the related data for the date using coding below :
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date='" & TxtReqDate.Text & "'"
it say invalid date.
i cannot change the date format in the database.
if i change the code TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy") TO TxtReqDate.Text = Calendar.SelectionStart.ToShortDateString as it will appear 02/18/2012 at the textbox the data will appear but i want 18/02/2012 to appear at the textbox.
You could make use of STR_TO_DATE function to parse that data and transform it into a Date value.
Use it like this (correct any syntactical error):
where do i should put it. example??
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date=STR_TO_DATE('" & TxtReqDate.Text & "','%d/%m/%Y')"
This example is actually using the OleDbCommand but the syntax is similar for the SqlCommand: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Dim comm As New OleDb.OleDbCommand(reportQueryString, conn)
comm.Parameters.Add("[ReportDate]", OleDbType.Date)
comm.Parameters("[ReportDate]").Value = dateVariable
You can see that when you add the parameter, you specify the dataType the command should convert your data type to. This way you're not doing raw string manipulation yourself.