Advertisement
Guest User

Insert

a guest
Jun 27th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Calendar;
  3.  
  4. /**
  5. * A Java MySQL PreparedStatement INSERT example.
  6. * Demonstrates the use of a SQL INSERT statement against a
  7. * MySQL database, called from a Java program, using a
  8. * Java PreparedStatement.
  9. *
  10. * Created by Alvin Alexander, http://alvinalexander.com
  11. */
  12. public class JavaMysqlPreparedStatementInsert
  13. {
  14.  
  15. public static void main(String[] args)
  16. {
  17. try
  18. {
  19. // create a mysql database connection
  20. String myDriver = "org.gjt.mm.mysql.Driver";
  21. String myUrl = "jdbc:mysql://localhost/test";
  22. Class.forName(myDriver);
  23. Connection conn = DriverManager.getConnection(myUrl, "root", "");
  24.  
  25. // create a sql date object so we can use it in our INSERT statement
  26. Calendar calendar = Calendar.getInstance();
  27. java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
  28.  
  29. // the mysql insert statement
  30. String query = " insert into users (Id, first_name, last_name,)"
  31. + " values (?, ?, ?)";
  32.  
  33. // create the mysql insert preparedstatement
  34. PreparedStatement preparedStmt = conn.prepareStatement(query);
  35. preparedStmt.setString (1, "Barney");
  36. preparedStmt.setString (2, "Rubble");
  37.  
  38. // execute the preparedstatement
  39. preparedStmt.execute();
  40.  
  41. conn.close();
  42. }
  43. catch (Exception e)
  44. {
  45. System.err.println("Got an exception!");
  46. System.err.println(e.getMessage());
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement