jtahstu的博客

Git仓库   英文博客  

最新碎语:以后没事写写小的知识点吧

您的位置:jtahstu的博客 >笔记> 大三下软件项目开发实训第五天 - JDBC封装

大三下软件项目开发实训第五天 - JDBC封装

UserInfo.java

package com.train.jdbc;
public class UserInfo {
 private String id;
 private String nameString;
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getNameString() {
  return nameString;
 }
 public void setNameString(String nameString) {
  this.nameString = nameString;
 }
 public UserInfo(String id, String nameString) {
  super();
  this.id = id;
  this.nameString = nameString;
 }
 public UserInfo() {
  super();
  // TODO Auto-generated constructor stub
 }
}

DAO.java

package com.train.jdbc;
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 DAO {
 private static final String DRIVER = "com.mysql.jdbc.Driver";
 private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
 private static final String USER = "jtahstu";
 private static final String PWD = "jtahstu";
 static List query(String sql) {
  List list = new ArrayList();
  try {
   Class.forName(DRIVER);
   Connection conn = DriverManager.getConnection(URL, USER, PWD);
   Statement stat = conn.createStatement();
   ResultSet rs = stat.executeQuery(sql);
   while (rs.next()) {
    String id = rs.getString("学号");
    String name = rs.getString("姓名");
    UserInfo d = new UserInfo(id, name);
    list.add(d);
   }
   conn.close();
   stat.close();
   rs.close();
  } catch (Exception e) {
   // TODO: handle exception
   System.out.println(e.getMessage());
   return null;
  }
  return list;
 }
 static void update(String sql) {
  try {
   Class.forName(DRIVER);
   Connection conn = DriverManager.getConnection(URL, USER, PWD);
   Statement stat = conn.createStatement();
   stat.executeUpdate(sql);
  } catch (Exception e) {
   // TODO: handle exception
   System.out.println(e.getMessage());
  }
 }
}

test.java

package com.train.jdbc;
import java.util.List;
public class test2 {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  // String sqlString="insert into test values('1','jtahstu')";
  // jdbc.update(sqlString);
  String sqlString = "select * from stulist where 行政班 like '计算机13_'";
  List list = DAO.query(sqlString);
  for (int i = 0; i < list.size(); i++) {
   UserInfo temp = (UserInfo) list.get(i);
   System.out.println(temp.getId() + "\t" + temp.getNameString());
  }
 }
}

---

本文章采用 知识共享署名2.5中国大陆许可协议 进行许可,欢迎转载,演绎或用于商业目的。

---

二维码加载中...

扫一扫移动端访问O(∩_∩)O

发表评论

54 + 66 =
路人甲 表情
看不清楚?点图切换 Ctrl+Enter快速提交
正在加载中……