Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. /* http://www.sqlitetutorial.net/sqlite-java/create-database/
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package aa;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.PreparedStatement;
  11. import java.sql.SQLException;
  12. import java.util.Scanner;
  13.  
  14. public class Insertadatos {
  15.  
  16. public static void main(String[] args) throws SQLException {
  17.  
  18. String url = "jdbc:mysql://localhost:3306/agenda";
  19. String user = "root";
  20. String password = "";
  21.  
  22. Connection myConn = null;
  23. PreparedStatement myStmt = null;
  24.  
  25. Scanner scanner = null;
  26.  
  27. try {
  28. // 0. read user input from command line: codigo nombre apellido tlf
  29. scanner = new Scanner(System.in);
  30.  
  31. /*System.out.print("Enter your last codigo: ");
  32. int codigo = scanner.nextInt();*/
  33.  
  34. System.out.print("Enter your last nombre: ");
  35. String nombre = scanner.next();
  36.  
  37. System.out.print("Enter your first apellido: ");
  38. String apellido = scanner.next();
  39.  
  40. System.out.print("Enter your tlf: ");
  41. String tlf = scanner.next();
  42.  
  43. // 1. Get a connection to database
  44. myConn = DriverManager.getConnection(url, user, password);
  45.  
  46. // 2. Create a statement
  47. String sql = "insert into agenda "
  48. + " (codigo, nombre, apellido, tlf)" + " values (null, ?, ?, ?)";
  49.  
  50. myStmt = myConn.prepareStatement(sql);
  51.  
  52. // set param values
  53. //myStmt.setInt(1, codigo);
  54. myStmt.setString(1, nombre);
  55. myStmt.setString(2, apellido);
  56. myStmt.setString(3, tlf);
  57.  
  58. // 3. Execute SQL query
  59. myStmt.executeUpdate();
  60.  
  61. System.out.println("Insert complete.");
  62. } catch (Exception exc) {
  63. exc.printStackTrace();
  64. } finally {
  65. if (myStmt != null) {
  66. myStmt.close();
  67. }
  68.  
  69. if (myConn != null) {
  70. myConn.close();
  71. }
  72.  
  73. if (scanner != null) {
  74. scanner.close();
  75. }
  76. }
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement