data can not save into mysql properly - java

I am trying to make login time and logout time web application in jsp netbeans. While i try to save logout time into mysql database the date & time save correctly but user name and password both save as null. Please help me to save user name and password correctly to table.
Here is my logout code:
`<%# page import ="java.sql.*" %>
`<%String url="jdbc:mysql://localhost:3306/mysql";`
` String user="root";`
` String password="";`
`Class.forName("com.mysql.jdbc.Driver");`
`Connection con = DriverManager.getConnection(url, user, password);`
`Statement st = con.createStatement();`
`String uname1= request.getParameter("first_name");`
`String pwd = request.getParameter("pass");`
`session.setAttribute("fname", uname1);`
`session.setAttribute("pass", pwd);`
`int i = st.executeUpdate("insert into logut values ('" + uname1 + "','" + pwd + "',now())");`
`if (i > 0) `
`{out.write("<script type='text/javascript'>\n");`
`out.write("alert(' Logout Successfully!!! ');\n");`
`out.write("setTimeout(function({window.location.href='index.jsp'},1000);");`
`out.write("</script>\n");`
`}`
%>`
My database save like this: id= null pass=null and date and time save correctly. help me out. Thank you advance.

There is a typo in your statement. I guess you mean the table logout
"insert into logut values ('" + uname1 + "','" + pwd + "',now())"
But aside this you really have to consider prepared statements.
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "username");
preparedStatement.setString(3, "password");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL statement
preparedStatement .executeUpdate();
Why prepared Statements:
difference-between-statement-and-preparedstatement
which-is-faster-statement-or-preparedstatement

Related

Change a line to prepared statement

statement.executeUpdate("INSERT INTO LOGIN VALUES(" + jTextField1.getText() + ",'" + jTextField2.getText() + "'," + jTextField3.getText() + ")");
I have this line and I am trying to do this line prepared statement but I am not able to do it.
What I did is this :
PreparedStatement pstmt = con.prepareStatement("UPDATE Login
SET login_id = ? WHERE username = ?");
the sql table is this
CREATE TABLE login(
login_id INTEGER PRIMARY KEY,
username varchar(150) NOT NULL,
password varchar(150) NOT NULL
);
This folwoing code should be encapsuled in a ty catch statment
Also i hope you add a password hashing function to your code, every thing else is very insecure.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO LOGIN VALUES (?,?,?)");
pstmt.setInt (1, Integer.parseInt(jTextField1.getText()));
pstmt.setString (2, jTextField2.getText());
pstmt.setString (3, jTextField2.getText()));
// execute the preparedstatement
pstmt.execute();
observed parameterized object to avoid SQL Injections. just a bunch of security. although that one, you have provided is Okay for learning purposes.

Connecting Form data to MySQL using JSP

I am trying to store the fields from a form in my web-page to a Database in MySQL using JSP. I do not get any errors but i don't see the data in my database when i hit submit. Please help me identify my problem. I have the following codes:
Sign up - New User
<div id="container">
<form action = "insertData.jsp" method = "post">
<table>
<tr><td>E-mail/username:</td><td><input type="text" name="e-mail"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td>First Name:</td><td><input type="text" name="fName"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lName"></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dateOfBirth"></td></tr>
<tr><td>Account Type:</td><td><input type="text" name="type"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</div>
</body>
and my JSP Code
<%
Connection con = null;
String email = request.getParameter("e-mail");
String password = request.getParameter("password");
String firstName = request.getParameter("fName");
String lastName = request.getParameter("lName");
String dob = request.getParameter("dateOfBirth");
String accountType = request.getParameter("type");
String queryText = "insert into user values('" + email + "'+'" + password + "','" + firstName + "','" + lastName + "','" + dob + "','" + accountType + "')";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "B#neswor1");
Statement stat = con.createStatement();
ResultSet rst = stat.executeQuery(queryText);
System.out.println("Data is successfully inserted!");
rst.close();
stat.close();
con.close();
} catch (Exception e) {
}
System.out.println("Success");
%>
Please help me identify what i am missing
The immediate cause of your problem is your insert query:
String queryText = "insert into user values('" + email + "'+'" +
password + "','" + firstName + "','" + lastName + "','" + dob + "','" +
accountType + "')";
If you look closely, there is no comma after the email literal. But you could have avoided this by using a prepared statement:
String sql = "insert into user values (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(insertTableSQL);
ps.setString(1, email);
ps.setString(2, password);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, dob);
ps.setString(6, accountType);
ps.executeUpdate();
Note that using a statement makes it much easier to see how your query string is being built. It also frees you from ugly string concatenation and escaping, which is error prone.
#duffymo pointed out many other potential problem with your code, some of which though should not necessarily cause it to crash. One other problem I see is that your date of birth field is being treated as a string, which it probably should be a date, and you should be inserting into your database as a date.
There are too many things wrong with this code:
Never, ever write scriptlet code in JSPs.
You have an empty catch block in that scriptlet code. If an exception is thrown you'll never know it.
Close resources in finally blocks.
You don't use PreparedStatement. You are asking for a SQL injection attack.
No XSS check.
No validation of input data.
Learn JSTL if you must use JSP.
Be aware that JSP model is vintage 1998. Modern UIs are done using HTML5, CSS3, and Javascript talking to REST services. The world has changed in the last 20 years. Tutorials exist for old technologies, but it doesn't mean they should be your first thought.

Add date from JXDatePicker into SQL Database in Netbeans

I would like to add a date value from JXDatePicker into my SQL database, however I'm getting this error when running it:
java.sql.sqldataexception: the syntax of the string representation of a datetime value is incorrect
This is my code:
try {
String url = "jdbc:derby://localhost:1527/Members";
String username = "admin1";
String password = "admin1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES('"+txtMemberID.getText()+"', '"+txtName.getText()+"', "
+ "'"+txtContact.getText()+"', '"+txtEmail.getText()+"', "
+ "'"+comboDate.getDate()+"', '"+comboTime.getSelectedItem()+"')";
stmt.execute(query);
JOptionPane.showMessageDialog(null, "Booking created");
txtMemberID.setText(null);
txtName.setText(null);
txtContact.setText(null);
txtEmail.setText(null);
comboDate.setDate(null);
comboTime.setSelectedItem("00");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
The datatype specified for the Date attribute in my database is Date.
Thank you.
Your problem is that you're trying to embed a Date value (or a String representation of one) into the INSERT statement. Instead of concatenating variables into the query literal, you should use parameterized SQL through a PreparedStatement. In addition to protecting your code from SQL injection, parameterized statements are re-usable by the database, which means that the DB doesn't need to parse the SQL before each execution -- this is especially important if you're running a large number of queries in a loop.
Another thing that you should take care of, is closing the resources you've opened. In your example code, the Connection and Statement are left open after they are no longer needed. This is easy to fix using the try-with-resources statement, which was introduced in Java 7. The resources declared within the try clause get automatically closed after the statement is executed.
Putting it all together, here's an example of what the modified code could look like:
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES(?, ?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, txtMemberID.getText());
ps.setString(2, txtName.getText());
ps.setString(3, txtContact.getText());
ps.setString(4, txtEmail.getText());
ps.setDate(5, new java.sql.Date(comboDate.getDate().getTime()));
ps.setString(6, comboTime.getSelectedItem().toString());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Booking created");
/*clear the UI components etc.*/
} catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString(), JOptionPane.ERROR_MESSAGE);
}

setting variables against data retrieved from a database

I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}

SQL update statement in Java

I am trying to update a field in my table using Netbeans and I have two conditions. The update statement is as follows:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and Check = ?";
try{
pst = conn.prepareStatement(sql1);
pst.setString(1, time);
pst.setString(2, username);
pst.setString(3, "IN");
pst.execute();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
but I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException: 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 'Check = 'IN' at line 1
How can I solve it?
"Check" is a reserved word, so you need to put it in backticks
Change it to:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and `Check` = ?";
For a list of reserved words, see here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Try using
pst.executeUpdate();
and also
is pst a PreparedStatement?
if not change it to that...
st.executeUpdate("update reservation set busname='" +
jTextField10.getText() + "',busno='" +
jTextField9.getText() + "',cusname='" +
jTextField8.getText() + "',noofpass='" +
jTextField7.getText() + "',amount='" +
jTextField6.getText() +"' where cusname='" +
jTextField8.getText() + "' ");

Categories

Resources