I'm making a StudentAdministration project with a Usercontroller, studentrepository, some html templates, a css stylesheet and a mySql database. Everything is working out great, and i see my index site, but im having problem creating students because of the Date attribute at my Student class.
In my controller, this is how i create:
#Override
public void create(Student st) {
jdbc.update("INSERT INTO studentdb.student(firstName, lastName,
enrollmentDate, password, cpr)
" + "VALUES('" + st.getFirstName() + "',
'" +
st.getLastName() + "', '" + st.getEnrollmentDate() + "', '" +
st.getPassword() + "', '" + st.getCpr() + "') ");
}
the problem is the st.getEnrollmentDate because it gives me another date format than the 1 MySql accepts. What should i do here? I'd rather not start changing the Date attribute to a String even though that would fix the problem.
You should be using prepared statements with parameter placeholders, and then use setDate. You should not concatenate values into a query string. That leaves you open to SQL injection.
As an example, you need to use:
Connection connection = ..; // defined elsewhere
try (PreparedStatement pstm = connection.prepareStatement(
"INSERT INTO studentdb.student(firstName, lastName, enrollmentDate, password, cpr) " +
" VALUES (?, ?, ?, ?, ?)") {
pstmt.setString(1, st.getFirstName());
pstmt.setString(2, st.getLastName());
// assuming getEnrollmentDate() returns a java.util.Date
pstmt.setDate(3, new java.sql.Date(st.getEnrollmentDate().getTime());
// In a real system you should never store passwords like this!!
pstmt.setString(4, st.getPassword());
// Assuming getCpr() returns string
pstmt.setString(5, st.getCpr());
pstmt.executeUpdate();
}
Note that storing a password like that should never be done. In a real system you would hash the password with something like PBKDF2 or bcrypt.
Try below Steps :-
1.Create a Date object.
Date now = new Date();
2.Create a SimpleDateFormat object by using the constructor,
String pattern = "yyyy-MM-dd";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
3.Now use the format() method to convert the date object to text format provided in the pattern.
String mysqlDateString = formatter.format(now);
Related
1- a me tried in this way
String sql = "insert into transport(s_id,transport_date)" +
" values ( + jTextField2.getText()+","
+ ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText() +")";
pst=con .prepareStatement(sql2);
pst.executeUpdate();
2- and this way
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String date=sdf.format(jDateChooser1.getDate());
String sql = "insert into transport(s_id,transport_date)" +
" values ( + jTextField2.getText()+","
+ date +")";
in #run
examble today choose : 2021-5-27
will insert 1989 !
Using + to place data in an SQL statement is EXTREMELY DANGEROUS. Aside from cross-site scripting, it is one of the greatest sources of hacks and vulnerabilities in software! For a more detailed explanation, search the web for “SQL injection”.
Do not, under any circumstances, place data in an SQL statement using concatenation (using + or StringBuilder or StringBuffer or Formatter or any other similar string construction mechanism).
The only safe way to add user-supplied data to a database statement is with PreparedStatement. The String argument you pass to prepareStatement must not have any data in it. Instead, you place question marks (?) in the String, to act as placeholders for data; then you use the various set* methods of PreparedStatement to replace each question mark with data. This allows the PreparedStatement to guarantee safety.
Instant instant = jDateChooser1.getDate().toInstant();
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
String sql = "insert into transport(s_id,transport_date) values (?, ?)";
pst = con.prepareStatement(sql);
pst.setString(1, jTextField2.getText());
pst.setObject(2, date);
pst.executeUpdate();
I generate this class in the entity object departments and I create log table called departments_log(department_id number, entry_user number,
entry_date date) when the method try to enter the deleted record into this table this error appears:
(inconsistent datatypes: expected DATE got NUMBER)
This is the do_dml method code :
if (operation == DML_DELETE) {
FacesContext context = FacesContext.getCurrentInstance();
UserInfo user =
(UserInfo)context.getExternalContext().getSessionMap().get("userInfo");
Number deptID = new Number(getDepartmentId());
Date entryDate = new Date(Date.getCurrentDate());
Number entryUser = new Number(user.getEmployeeId());
String sql =
"insert into departments_log (DEPARTMENT_ID,entry_user,entry_date) values (" +
deptID + "," + entryUser + "," +
entryDate + ")";
PreparedStatement stm =
getDBTransaction().createPreparedStatement(sql, 1);
try {
stm.executeUpdate(sql);
} catch (SQLException f) {
System.out.println("delete errore"+f.getMessage()+Date.getCurrentDate());
}
}
The problem is that you are not passing the data correctly: you are inlining the values (which is a major security risk in itself) rather than passing them through query parameters.
Here is how you can fix it:
String sql = "insert into departments_log (DEPARTMENT_ID,entry_user,entry_date) values (?,?,?)";
PreparedStatement stm = getDBTransaction().createPreparedStatement(sql, 1);
stm.setInt(1, deptID);
stm.setString(2, entryUser.longValue());
stm.setDate(entryDate);
The above is only a skeleton of an implementation. You would need to add null checking of dates and Numbers, and make other modifications that improve robustness.
Link to a tutorial on using parameteriszed prepared statements.
So I created the following function to write to a database:
public static void updateBuyer(String ID, String name, Location latlong) {
float lat = latlong.latitude;
float lon = latlong.longitude;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
// conn =
// DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?user=testuser&password=testpassword");
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String sql = "UPDATE Buyer " + "SET latitude ="
+ Float.toString(lat) + " WHERE idBuyer in (" + ID + ")";
String sql2 = "UPDATE Buyer " + "SET longitude ="
+ Float.toString(lon) + " WHERE idBuyer in (" + ID + ")";
String sql3 = "UPDATE Buyer " + "SET Name =" + name
+ " WHERE idBuyer in (" + ID + ")";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
conn.close();
} catch (Exception e) {
System.err.println(e);
}
}
Lets say I passed the following parameters:
(12,craigs,location object)
Now when I run the function I get the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'craigs' in 'field list'
12 is the ID i retrieved from the databases earlier,
craigs is the random name I am trying to insert, and
location object is just a set of coordinates (lat,long)
Which leads me to think that it is looking for a field called "craigs" in the table for some reason, but why would it do that?
The problem is that you've got SQL like this:
UDPATE Buyer SET Name = craigs WHERE idBuer in (Whatever)
That's trying to copy the value from a column named "craigs".
Now you could just add apostrophes - but don't. Instead, use parameterized SQL with a prepared statement. That way you'll avoid SQL injection attacks, your code will be simpler, and you'll avoid unnecessary string conversions which can cause problems, particularly with date values.
Additionally, you only need a single statement, which can update all three columns:
String sql = "UPDATE Buyer SET Name=?, latitude=?, longitude=? WHERE idBuyer=?";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, name);
statement.setFloat(2, lat);
statement.setFloat(3, lon);
statement.setString(4, ID);
statement.executeUpdate();
}
(Note that I've assumed you're actually only trying to update a single buyer - it's not clear why you were using IN at all. Also note that I'm using a try-with-resources statement, which will automatically close the statement afterwards.)
Additionally, I would *strongly *advise you to avoid just catching Exception. Catch SQLException if you must - but you'd actually probably be better letting it just propagate up the call stack.
I am trying to insert user information taken from a registration form into Derby DB using a java servlet class.
I get connected to the DB on NetBeans right after the user clicks the submit button with the user's information filled out. Then it should run this method:
public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
try {
stmt = conn.createStatement();
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
System.out.println(insertNewUserSQL);
stmt.executeQuery(insertNewUserSQL);
stmt.close();
} catch(SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
But I keep getting the following exception:
java.sql.SQLException: executeQuery method can not be used for update.
What does this mean exactly?
The SQL command is correct as I can do it manually on NetBeans SQL Command window.
Are there restrictions for servlets or something I don't know about?
Thanks in advance!
Since you are inserting a record, you should be using executeUpdate() not executeQuery().
Here are some methods that are usually misused:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.
One more thing, your query is weak as it is vulnerable with SQL Injection. Please do parameterized by using PreparedStatement.
Sample Code Snippet:
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
Java PreparedStatement
To update values you need to use an updatable ResultSet, as follows:
ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();
Alternatively, you can use the executeUpdate method of statement, as follows:
statement.executeUpdate("update table set id = 2");
Relatively new to using database and for some reason I can't get this 'execute' to work.
statment2.execute("insert into table Value (" + int + "," + date + "," + int + ",'" + string + "')");
The error I get is "missing a comma". The date is designated as dates only in that particular field.
I set it up as follows
Date date = new Date();
date.setMonth(month);
date.setYear(year);
date.setDate(weekStart); //weekStart is always monday
Do I need to use just plain old date or date.toString? I was going to use Calendar but I don't know how to set a DB date using the Calendar object. I didn't see a "gety/m/d" method.
So, is the problem my query or am I improperly using the Date object to set the date in the database?
Edit:
Tried the response, got incorrect format - Expected Date got number.
Tried
sqlDate.valueOf(dateString I created)
sqlDate.toString()
sqlDate
Using a preparedStatement wouldn't fix this would it? I realize it's supposed to be better for security reasons.
First, you should use a PreparedStatement to insert values in your query. This has many advantages including avoiding SQL Injection issues. If you use PreparedStatement, you will be avoid the errors that you are seeing now. Your code using PreparedStatement would something like this:
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "insert into table (column1,column2,column3,column4) values(?, ?, ?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 1);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, 3);
pstmt.setString(3, "test");
pstmt.executeUpdate();
} catch (Exception e) {
//log the error messages log.error(e,e);
//throw the actual exception upstream
} finally {
pstmt.close();
conn.close();
}
I am not sure what you meant by "DB" date. If you are after the sql date object you can convert a java.util.Date object to a java.sql.Date object this way:
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());