扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
在本页阅读全文(共2页)
1.mysql在本地localhost的test数据库 建person表,暂以字段id,name,password ,表中可输入一行值.
2.建类 DAOUtil
import java.sql.Connection;
import java.sql.DriverManager;
public class DAOUtil {
public DAOUtil() {
}
public static Connection getConn() {
Connection conn = null;
String db_url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gb2312";
String db_user = "root";
String db_password= "admin";
String db_driver = "com.mysql.jdbc.Driver";
try {
Class.forName(db_driver);
conn = DriverManager.getConnection(db_url, db_user, db_password);
} catch (Exception ex) {
ex.printStackTrace();
}
return conn;
}
/**
* dbclose
* 关闭Connection,Statement
* @param conn Connection
* @param stmt Statement
*/
public static void dbclose(Connection conn, Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.建类 PersonDAO
import java.util.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
public class PersonDAO {
static PersonDAO pdao;
public static PersonDAO getInstance() {
if (pdao == null) {
synchronized (PersonDAO.class) {
pdao = new PersonDAO();
}
}
return pdao;
}
public PersonDAO() {
super(); }
public static void main(String[] args) {
System.out.println("person==="+PersonDAO.getInstance().getPersonInfo());
}
private static List getPersonInfo() {
String name = "";
String password = "";
Connection conn = null;
List list = new java.util.ArrayList();
Statement stmt = null;
String sql =
"select name,password from person";
try {
conn = DAOUtil.getConn();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
name = (String)rs.getString("name");
password = (String)rs.getString("password");
list.add(name+","+password);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DAOUtil.dbclose(conn, stmt);
}
return list;
}
}
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者