java通过JDBC操作mysql数据库

时间:2022-10-02 15:37:38
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 {

/**
* 入口函数
*
* @param arg
*/
public static List<String> queryUserClosed(String today,String lastMonday) {
List<String> beanList = new ArrayList<String>();
try {
Connection con = null; // 定义一个MYSQL链接对象
Class.forName("com.mysql.jdbc.Driver").newInstance(); // MYSQL驱动
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db?useUnicode=true&characterEncoding=UTF-8",
"root", ""); // 链接本地MYSQL
Statement stmt; // 创建声明
stmt = con.createStatement();

// 查询数据并输出
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()) { // 循环输出结果集
beanList.add(selectRes.getString("reason"));
}
} catch (Exception e) {
e.printStackTrace();
System.out.print("MYSQL ERROR:" + e.getMessage());
}
return beanList;
}
}

java连接mysql时,需要安装驱动。如果未安装,会出现找不到“com.mysql.jdbc.Driver”的错误。

jar包 免费下载地址:http://download.csdn.net/detail/tolcf/9555814