This article describes the Java method of implementing a JDBC-based operation of mysql database. Share it for your reference, as follows:
package main;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;public class DBConnection { /** * Entry function* * @param arg */ public static List<String> queryUserClosed(String today,String lastMonday) { List<String> beanList = new ArrayList<String>(); try { Connection con = null; // Define a MYSQL link object Class.forName("com.mysql.jdbc.Driver").newInstance(); // MYSQL driver con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/my_db?useUnicode=true&characterEncoding=UTF-8", "root", ""); // Link local MYSQL Statement stmt; // Create declaration stmt = con.createStatement(); // Query data and output StringBuffer sql = new StringBuffer(); sql.append(" select reason"); sql.append(" from t1"); sql.append(" GROUP BY reason"); String selectSql = sql.toString(); ResultSet selectRes = stmt.executeQuery(selectSql); while (selectRes.next()) { // Loop output result set beanList.add(selectRes.getString("reason")); } } catch (Exception e) { e.printStackTrace(); System.out.print("MYSQL ERROR:" + e.getMessage()); } return beanList; }}When connecting to mysql in Java, you need to install the driver. If not installed, an error "com.mysql.jdbc.Driver" cannot be found.
Click here to download the jar package.
For more information about Java-related content, please check out the topics of this site: "Java+MySQL database programming summary", "Java data structure and algorithm tutorial", "Java file and directory operation skills summary", "Java operation DOM node skills summary" and "Java cache operation skills summary"
I hope this article will be helpful to everyone's Java programming.