Advertisement
Guest User

Untitled

a guest
Nov 3rd, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DatabaseMetaData;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.sql.*;
  10.  
  11. public class DBExample2 {
  12.  
  13. public static void main(String[] args) {
  14. List<String> list1 = GetAllProductName();
  15. for (String item : list1) {
  16. System.out.println(item);
  17. }
  18. InsertProduct("582115545", "qwerty", "19"
  19. + "19");
  20. list1 = GetAllProductName();
  21. for (String item : list1) {
  22. System.out.println(item);
  23. }
  24. }
  25.  
  26. public static List<String> GetAllProductName() {
  27. Connection conn = null;
  28. ArrayList<String> productlist = new ArrayList<String>();
  29. try {
  30. String dbURL = "jdbc:sqlserver://LAB324-11\\LAB324;DatabaseName=Lab31116";
  31. String user = "sa";
  32. String pass = "582115045";
  33. conn = DriverManager.getConnection(dbURL, user, pass);
  34. if (conn != null) {
  35. Statement m_Statement = conn.createStatement();
  36. String query = "SELECT * FROM student";
  37. ResultSet m_ResultSet = m_Statement.executeQuery(query);
  38. while (m_ResultSet.next()) {
  39. productlist.add(m_ResultSet.getString(1) + "," + m_ResultSet.getString(2));
  40. }
  41. }
  42. } catch (SQLException ex) {
  43. ex.printStackTrace();
  44.  
  45. } finally {
  46. try {
  47. if (conn != null && !conn.isClosed()) {
  48. conn.close();
  49. }
  50. } catch (SQLException ex) {
  51. ex.printStackTrace();
  52. }
  53. }
  54. return productlist;
  55. }
  56.  
  57. public static void InsertProduct(String id, String Name,String Age) {
  58. Connection conn = null;
  59. ArrayList<String> productlist = new ArrayList<String>();
  60.  
  61. try {
  62. String dbURL = "jdbc:sqlserver://LAB324-11\\LAB324;DatabaseName=Lab31116";
  63. String user = "sa";
  64. String pass = "582115045";
  65. conn = DriverManager.getConnection(dbURL, user, pass);
  66. if (conn != null) {
  67. Statement m_Statement = conn.createStatement();
  68. String query = "Insert into student (StudentId,StudentName,StudentAge) values('" + id + "','" + Name + "','" + Age + "')";
  69. m_Statement.execute(query);
  70. }
  71. } catch (SQLException ex) {
  72. ex.printStackTrace();
  73. } finally {
  74. try {
  75. if (conn != null && !conn.isClosed()) {
  76. conn.close();
  77. }
  78. } catch (SQLException ex) {
  79. ex.printStackTrace();
  80. }
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement