Java mysql database and content query instance code

  • 2020-05-12 02:43:02
  • OfStack

Java mysql database and perform content queries

Recently, I have done several projects with the framework, and I felt that I had forgotten the underlying things at the beginning. I wrote a simple connection code of JDBC to familiarize myself with the review 1, and I hope it will be helpful to the novice who just came into contact with it. This is also my first essay, no more nonsense, directly on the code:


 public Connection getCon() {
    // Database connection name 
    String username="root";
    // Database connection password 
    String password="";
    String driver="com.mysql.jdbc.Driver";
    // Among them test Is the database name 
    String url="jdbc:mysql://localhost:3306/test";
    Connection conn=null;
    try{
      Class.forName(driver);
      conn=(Connection) DriverManager.getConnection(url,username,password);
    }catch(Exception e){
      e.printStackTrace();
    }
    return conn;
  } 

With the above code, you can connect to the database directly. Of course, you must import the relevant jar package mysql-connector-java-5.1.5-bin.jar (you can download it from baidu). And here's how to do it:


public List<String> getSelect() { 
     // sql statements 
    String sql = "select * from user"; 
     //  Get to the connection 
    Connection conn = getCon();
    PreparedStatement pst = null;
    //  define 1 a list Used to accept queries from the database 
    List<String> list = new ArrayList<String>();
    try {
      pst = (PreparedStatement) conn.prepareStatement(sql);
      ResultSet rs = pst.executeQuery();
      while (rs.next()) {
        //  Adds the queried content to list In which userName Is the name of a field in the database 
        list.add(rs.getString("userName"));
      }
    } catch (Exception e) {
    }
    return list;
  }

At this point, you can query the data in the database. The database name I used in the test is test, and the name of the newly created table is user. There is only one userName in the field, and you can add it according to your own needs.


public static void main(String[] args) {
     // Among them TestDao As the name of the class 
    TestDao dao = new TestDao();
     // new 1 a list Gets the collection returned in the query method 
    List<String> list = dao.getSelect();
     // To get the list Traverse the output to the console 
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
    }
  }

For convenience, the above three methods are written in the TestDao class. Of course, after copying the code, you need to import the corresponding package. The shortcut key of the import package is Ctrl+Shift+O

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: