I was doing an assignment and had an update class which accepted the SQL and updated table. I am using Java. I did it this way
sqls = "INSERT INTO statistics(ID, TeamName, Wins, Draws, Losses, Points, DatePlayed) VALUES ( 0 ,'"+var1+"',"+var2+","+var3+","+var4+","+var5+",'"+ date +"')";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/players","root", "123");
stmt = con.prepareStatement(sqls);
int updaterows = stmt.executeUpdate(sqls);
my teacher did it this way
sqls = "INSERT INTO statistics(TeamName, Wins, Draws, Losses, Points, DatePlayed) VALUES ( ?,?,?,?,?,?)"
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/players","root", "123");
stmt = con.prepareStatement(sqls);
stmt.setString(1, var1);
stmt.setInt(2, var2);
stmt.setInt(3, var3);
stmt.setInt(4, var4);
stmt.setInt(5, var5);
stmt.setTimestamp(6, var6);
int updaterows = stmt.executeUpdate();
which one is better and why please it really got me confused as both methods worked.
Definitely use the second way – the teacher’s way. Your way is very dangerous, because the code is prone to sql injection. Any person could enter
DROP DATABASEasTeamNameand your database will be gone.P.S Some fun – Bobby Tables.