Java mysql database and perform content query
I have recently used a framework to do several projects. I feel that I have forgotten the underlying stuff at the beginning. I wrote a simple JDBC connection code to familiarize myself with it and review it. I also hope it will be helpful to newbies who are new to it. This is also my first essay. Without further ado, just enter the code:
public Connection getCon() { //Database connection name String username="root"; //Database connection password String password=""; String driver="com.mysql.jdbc.Driver"; //Where 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; }You can directly connect to the database through the above code. Of course, you must import the relevant jar package mysql-connector-java-5.1.5-bin.jar that connects to the database (can be downloaded on Baidu). Then the following is the query method:
public List<String> getSelect() { // sql statement String sql = "select * from user"; // Get the connection Connection conn = getCon(); PreparedStatement pst = null; // Define a list to accept the content of the database query List<String> list = new ArrayList<String>(); try { pst = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { // Add the queryed content to the list, where userName is the field name in the database list.add(rs.getString("userName")); } } catch (Exception e) { } return list; } At this time, you can query the data in the database. The database name I used when I tested was test, the name of the newly created table was user, and the fields in it were only one userName. You can add it according to your needs. The following is a test of the above content:
public static void main(String[] args) { // where TestDao is the class name TestDao dao = new TestDao(); // Create a new list to get the collection returned in the query method List<String> list = dao.getSelect(); // traverse the obtained list and output it 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 to import the package is Ctrl+Shift+O. If there are any shortcomings or errors, I hope everyone points out it out and look forward to everyone's progress together.
Thank you for reading, I hope it can help you. Thank you for your support for this site!