This is my code for insert data in order colunm but my confusion is that what type of value i provide in users_id which is foriegn key in order table i want that users_id give value through session of currently logged user which want to place order and its id is save aginst his order record code is here.
<% request.getSession().getAttribute("users_id");%>
<% String add = request.getParameter("add");
String type = request.getParameter("order_type");
String city = request.getParameter("city");
String veh = request.getParameter("vehicles");
String date = request.getParameter("order_date");
String users_id = request.getParameter("users_id");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/auto_lube","root", "mehar");
Statement st = con.createStatement();
System.out.println(add);
//ResultSet rs;
int i = st.executeUpdate("INSERT INTO `user_order` (`id`, `address`, `order_type`, `city`, `vehicle`, `order_date`, `users_id`) VALUES (NULL, '"+add+"', '"+type+"', '"+city+"', '"+veh+"', '2','"+users_id+"')");
%>
The first thing is that try to avoid code on JSP or any design pages you use. Because due to any problem page crashed then your code will be shown on page. So use backend tool like servlet but that is quite old but for shake of learning you can use it. If possible then use hibernate, it provide very great support.
and pass your data to java code then access data of session.
if possible then pass order detail using JSON, that will be quite helpful while storing data and access it and change it any place.
Suppose you want to edit quantity of ordered item or etc, then json will be useful, each time you never have to send request to server.
Use prepared statement for to enter data in DB.
and make table order that have only order detail like user id (get from session) and order number.
and other table ordermaster that have order number and item ordered and it's quantity and price and ordered time and other details you want. so here order id of ordermaster will be foreign key in order table.
Related
Say I have a table named users and a column named username with the format user1, user2 ..
I want to insert users into this table in a loop and value of every entry depends on the one's before. Value of the new entry is generated by the alphabetically greatest entry in the table, namely users.
Since it's possible in JDBC API to getGeneratedKeys after an insert while AutoCommit set to false;
In a situation like given below:
connection.setAutoCommit(false);
while(someCondition)
{
ResultSet rs = connection.createStatement("select max(username) from users").executeQuery();
if(rs.next())
{
name= rs.getString("username"); //returns user1
}
String newName = generateNewName(name); // simply makes user1 -> user2
connection.createStatement("insert into users (name,...) values ("+newName+",...)").executeUpdate(); ///and inserts..
}
does the select query return the last inserted value
or
it returns the max column in the table before I start the loop ?
First, to make sure you see all changes on the database immediately prefer TransactionIsolation of READ_UNCOMMITED over using auto commit. Alternatively using auto commit everywhere would do the job, too.
Once you made sure you see every db change immediately, the database will send you the maximum user from some time during the selects execution. But once you actually receive the result there might be additional users created by others threads. Thus this will only work for a single thread working and most likely that doesn't make any sense nowadays.
TL:DR
No, don't do it!
Here's what I'm attempting to do. I have a Java program that decomms a telemetry stream into the individual raw fields. I am passing these raw fields values into a MySQL table where each column is one of the fields. In this database I also have a view that grabs all the telemetry data and calculates a few new derived columns based on raw data (e.g. raw counts to engineering units). In my Java program, after insertion I would like to grab the corresponding row from the VIEW (raw + derived) and pass that data along elsewhere.
Originally I thought I could simply insert the raw data into the VIEW and have the row returned to me in a ResultSet in the Java program. Unfortunately the data isn't returned in a ResultSet.
What I'm attempting to do now is insert the raw data into the table (this part works), get the primary key, then lookup the row from the VIEW. The part I'm struggling with is retrieving the primary key from the INSERT. I'm using a PreparedStatement generated from my Connection object and have supplied it with Statement.RETURN_GENERATED_KEYS. However, when I call getGeneratedKeys() on my statement after I call executeUpdate() my ResultSet is always empty. I can watch it insert the rows into the table while it's running...what am I doing wrong?
Can I not retrieve the generated primary key in this fashion if the primary key is generated via a trigger?
UPDATE: I've tried swapping out the Statement.RETURN_GENERATED_KEYS for a String array with the name of the primary key column, but that doesn't seem to work either.
I apologize for not including my code, but it would be difficult for me to do so. I've attempted to describe what I'm doing to the best of my abilities.
Ive seen this in another post. That claimed to work. Is this what yours looks like?
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getInt(1);
}
I have used SP's and here is an example of what I did. I used an in/out parm to get it back...
CREATE DEFINER=`scaha`#`localhost` PROCEDURE `updateprofile`(
IN in_idprofile INT(10),
IN in_usercode VARCHAR(50),
IN in_pwd VARCHAR(50),
IN in_nickname VARCHAR(50),
IN in_isactive tinyint,
IN in_updated timestamp,
OUT out_idprofile INT(10))
BEGIN
/* If the idprofile is < 1 then we insert a new record.. */
/* otherwise its an update */
if (in_idprofile < 1) then
insert into scaha.profile (usercode, pwd, nickname, isactive,updated) values (in_usercode,in_pwd,in_nickname,in_isactive,in_updated);
SET out_idprofile = LAST_INSERT_ID();
else
update scaha.profile set usercode = in_usercode, pwd = in_pwd, nickname = in_nickname, isactive = in_isactive, updated = in_updated
where idprofile = in_idprofile;
SET out_idprofile = in_idprofile;
end if;
END
I have a table with a column that I want to insert data into but not existing data.
To give an example I have a day column and a customer. The same customer cannot have the same date twice, so I have a customer named Karl and he is on monday. If I try to add Karl to monday, when he is already existing on monday, it should not do that. How do I do this? Assuming I am using JTextFields to type the name and day.
So far I got this to insert data which works (though without checking if it's already existing!)
s.executeQuery ("SELECT * FROM customer");
s.executeUpdate("INSERT INTO customer values ('"+name.getText()+"', '"+day.getText()+"')");
How do I check if what I type in name textField and day textField both exist in same row?
Thanks in advance
try this
PreparedStatement s = connection.prepareStatement("SELECT * FROM customer WHERE name=? AND date=?");
s.setString(1, name.getText());
s.setString(2, day.getText());
ResultSet result = s.executeQuery ();
if(result.next()) {
// dupilcate records present. don't add
} else {
// add records to table.
s.executeUpdate("INSERT INTO customer values ('"+name.getText()+"', '"+day.getText()+"')");
}
From the database perspective, #Kocko has already suggested that you can create a unique constraint.
Now, if you want to check as you type in your textbox then you can cache the data from the table and then check as you type or finish typing, but you need to consider points like who all can insert etc.
You can also use Ajax for help which silently goes to server without loading whole page.
In my java program I used Hybernate technology to access MySQL database table called items .That table has columns named "itemname itemprice itemid" & my java program has HQL statements to fetch data. Also it has a combo box which populates from the items table. Once we select an itemname from combo box it automatically fill two non editable jtext fields called itemid & itemprice, & another part of the program has codes to get string values from those jtextfields & write those values in another database table called orders using a POJO class.
I want to know that this kind of program can be attacked by sql injections ???, if we use Hibernate it is safe from sql injection attacks ???....
If my program has security threats briefly explain how can I avoid those...
I post some codes here.
This statement to fill combo box
String SQL_QUERY = "Select items.iname,items.iid,items.iprice from Item items";
This statement fills jtextfields. The "selecteditem" variable is the selected index of the combo box.
String SQL_QUERY ="Select items.iname,items.iid,items.iprice from Item items where items.iid = '"+selecteditem+"'";
This method writes data in orders table
//To send data to the orders table
private void fillordertable(){
String itemname = (String) jcbItemCode.getSelectedItem();
String itempric = jtfItemPrice.getText();
String tmp = jtfQuantity.getText();
int itemqty = Integer.parseInt(tmp);
String temp = jtfUnitPrice.getText();
double unitpric = Double.parseDouble(temp);
Session session = null;
//This variables for validating purposes
String tempcname = jtfName.getText();
String tempcemail = jtfEmail.getText();
if(tempcname.equals("") || tempcemail.equals("")){
jtaDisplay.setText("Check * fields");
}
else{
try{
SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
session.beginTransaction();
Order order = new Order();
order.setItcode(itemcode);
order.setItdiscription(itemdis);
order.setItqty(itemqty);
order.setItemprice(unitpric);
order.setTotprice(unitpric * itemqty);
order.setOstatus("Placed");
session.save(order);
session.getTransaction().commit();
}
catch(Exception exc){
jtaDisplay.setText(exc.getMessage());
}
finally{
session.flush();
session.close();
}
jtaDisplay.setText("Order & customer tables updated successfully !!!");
}
}
It is difficult to understand my whole code if I post it here. So I have posted some codes which I thought helpful to answer my question. If that is not enough please comment.
Thanks!
String SQL_QUERY ="Select items.iname,items.iid,items.iprice from Item items where items.iid = '"+selecteditem+"'";
is susceptible to sql injection if selectedItem is data entered by the user.
Generating SQL or HQL queries by concatenating strings is in general bad form, and likely to lead to sql injection possibilities.
The safe way is to use named parameters in any SQL or HQL.
In your example, which appears to be SQL, after acquiring a Hibernate session, something like:
String SQL_QUERY ="Select items.iname,items.iid,items.iprice from Item items where items.iid = :selecteditem";
SQLQuery query = session.createSQLQuery(SQL_QUERY);
query.setParameter("selecteditem", selecteditem);
List<Object[]> results = query.list();
should be approximately the way you want to code and execute your query.
Similar things apply to HQL.
If you just concatenate strings, the evil values entered by a hacker as in the famous xkcd become part of your query and can do awful things.
If this is not a web form but a desktop application, you may well be in complete control of the values that can get into this variable, but it's still advisable to try to do these things correctly.
Another effect of named parameters is that the parametrized sql can be cached and reused for different values of the parameter. So it's a good idea even without the security concern.
if you are creating HQL by concatenating field values with the rest of the HQL text, you have a problem. if you are using HQL (correctly) with substitution variables for all field values, you are fine. (obviously there could be more to say about this, but without more details from the OP, this is about all we can say at this time). also, if you insert/update logic is purely using POJOs, then you are fine there.
UPDATE:
now that you've posted some code, yes you have problems. you should use named parameters in your HQL. (your write code is fine, though).
I am currently trying to make an update application (Java based) that the user can go through and view the existing database entries (MySQL) and edit them if need be... I was wondering how to get the information for a specific entry (ie 12-1589 which is an example of what the ID or primary key would be) and fill in the text boxes with all of the information from said entry.... I may just need to walk away from the computer for a bit because i may be over-thinking it, but I don't know...
mainly i am unsure with the exact code that you would use to move to that entry and retrieve the data from just that entry.... I know how to step trough a database one entry at a time, but i would rather just jump to a specific row based off of an id number (such as above 12-1589) if at all possible....
I just tried this and i recieved an error.... The error was:
"Unknown column '12-1859' in 'where clause'"
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement();
String sql = "SELECT * FROM Load_Sheet WHERE Load_Number = 12-1859 limit 1";
rs = stmt.executeQuery(sql);
String BC = rs.getString("BC");
If anyone could give me a hand with that is going wrong i would appreciate it...
I just started getting another error along with the other one... it is :
"illegal operation on empty result set"
Though the result sets are not empty so my guess is, is that i am missing a step somewhere....
What you need is a simple WHERE statement if i understood correctly your question.
SELECT * FROM table_name WHERE entry_col = "12-1589" LIMIT 1
LIMIT 1 is only added so that the MySql query only returns a single row.