Advertisement
Guest User

Untitled

a guest
Apr 6th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.Statement;
  4. import java.sql.SQLException;
  5.  
  6. public class SelectStatementSample
  7. {
  8. public static void main(String[] args) throws Exception
  9. {
  10. Connection connection = null;
  11. try
  12. {
  13. // Register MySQL JDBC driver to be known by
  14. // the DriverManager object.
  15. Class.forName("com.mysql.jdbc.Driver");
  16.  
  17. // Get a connection to database. We prepare the
  18. // connection information here such as database
  19. // url, user and password.
  20. String url = "jdbc:mysql://localhost/testdb";
  21. String user = "root";
  22. String password = "";
  23. connection = DriverManager.getConnection(url,
  24. user, password);
  25.  
  26. // Create a statement object instance from the
  27. // connection
  28. Statement stmt = connection.createStatement();
  29.  
  30. // We are going to execute an insert statement.
  31. // First you have to create a table that has an
  32. // ID, NAME and ADDRESS field. For ID you can use
  33. // an auto number, while NAME and ADDRESS are
  34. // VARCHAR fields.
  35. String sql = "INSERT INTO users (name, address) " +
  36. "VALUES ('Foo Bar', 'Some Street')";
  37.  
  38. // Call an execute method in the statement object
  39. // and passed the sql or query string to it.
  40. stmt.execute(sql);
  41.  
  42. // After this statement is executed you'll have a
  43. // record in your users table.
  44. } catch (ClassNotFoundException e)
  45. {
  46. System.err.println("Could not load database driver!");
  47. } catch (SQLException e)
  48. {
  49. e.printStackTrace();
  50. } finally
  51. {
  52. if (connection != null)
  53. {
  54. connection.close();
  55. }
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement