java查询数据库,java查询数据库表并输出

发布时间:2023-01-03

本文目录一览:

  1. java中,用DAO查询一个数据库步骤,分哪几个步骤,原理解析
  2. java程序操作MySQL数据库
  3. java 查询数据库怎么循环输出?
  4. Java怎么查询出数据库当前月份的数据并返回给前端
  5. java中怎么把数据库中数据查询出来
  6. 如何用Java实现数据库查询

java中,用DAO查询一个数据库步骤,分哪几个步骤,原理解析

创建一个以JDBC连接数据库的程序,包含7个步骤:

1、加载JDBC驱动程序:

在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机),这通过java.lang.Class类的静态方法forName(String className)实现。 例如:

try {
    // 加载MySql的驱动类
    Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
    System.out.println("找不到驱动程序类,加载驱动失败!");
    e.printStackTrace();
}

成功加载后,会将Driver类的实例注册到DriverManager类中。

2、提供JDBC连接的URL

  • 连接URL定义了连接数据库时的协议、子协议、数据源标识。
  • 书写形式:协议:子协议:数据源标识 协议:在JDBC中总是以jdbc开始
    子协议:是桥连接的驱动程序或是数据库管理系统名称
    数据源标识:标记找到数据库来源的地址与连接端口 例如:(MySql的连接URL)
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk

useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为gb2312GBK,本参数必须设置为truecharacterEncoding=gbk:字符编码方式。

3、创建数据库的连接

要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,该对象就代表一个数据库的连接。 使用DriverManagergetConnection(String url, String username, String password)方法传入指定的欲连接的数据库的路径、数据库的用户名和密码来获得。 例如:

// 连接MySql数据库,用户名和密码都是root
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
try {
    Connection con = DriverManager.getConnection(url, username, password);
} catch (SQLException se) {
    System.out.println("数据库连接失败!");
    se.printStackTrace();
}

4、创建一个Statement

要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3种类型:

  1. 执行静态SQL语句。通常通过Statement实例实现。
  2. 执行动态SQL语句。通常通过PreparedStatement实例实现。
  3. 执行数据库存储过程。通常通过CallableStatement实例实现。 具体的实现方式:
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(sql);
CallableStatement cstmt = con.prepareCall("{CALL demoSp(?, ?)}");

5、执行SQL语句

Statement接口提供了三种执行SQL语句的方法:executeQueryexecuteUpdateexecute

  1. ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句,返回一个结果集(ResultSet)对象。
  2. int executeUpdate(String sqlString):用于执行INSERT、UPDATE或DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等。
  3. boolean execute(String sqlString):用于执行返回多个结果集、多个更新计数或二者组合的语句。 具体实现的代码:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...");
int rows = stmt.executeUpdate("INSERT INTO ...");
boolean flag = stmt.execute(String sql);

6、处理结果

两种情况:

  1. 执行更新返回的是本次操作影响到的记录数。
  2. 执行查询返回的结果是一个ResultSet对象。
  • ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些行中数据的访问。
  • 使用结果集(ResultSet)对象的访问方法获取数据:
while (rs.next()) {
    String name = rs.getString("name");
    String pass = rs.getString(1); // 此方法比较高效
}

(列是从左到右编号的,并且从列1开始)

7、关闭JDBC对象

操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声明顺序相反:

  1. 关闭记录集
  2. 关闭声明
  3. 关闭连接对象
if (rs != null) { // 关闭记录集
    try {
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
if (stmt != null) { // 关闭声明
    try {
        stmt.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
if (conn != null) { // 关闭连接对象
    try {
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

java程序操作MySQL数据库

数据库内容

Java源代码(代码实现的是查询成绩为 的人员信息 至于其他功能的 代码中有注释)注意:在Eclipse里运行程序的时候,要工程里插入jar包,否则运行异常!

import java.sql.*;
import java.io.*;
class database_manage {
    public Connection conn = null;
    public ResultSet rs = null;
    private String DatabaseDriver = "com.mysql.jdbc.Driver";
    private String DatabaseConnStr = "jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8";
    private String username = "root";
    private String password = "root";
    public void setDatabaseDriver(String Driver) {
        this.DatabaseDriver = Driver;
    }
    public String getDatabaseDriver() {
        return (this.DatabaseDriver);
    }
    public void setDatabaseConnStr(String ConnStr) {
        this.DatabaseConnStr = ConnStr;
    }
    public String getDatabaseConnStr() {
        return (this.DatabaseConnStr);
    }
    public database_manage() { // 构造函数连接数据库
        try {
            Class.forName(DatabaseDriver);
        } catch (java.lang.ClassNotFoundException e) {
            System.err.println("加载驱动器有错误:" + e.getMessage());
            System.out.print("执行插入有错误:" + e.getMessage()); // 输出到客户端
        }
    }
    public ResultSet query(String sql) { // 查询数据库
        rs = null;
        try {
            conn = DriverManager.getConnection(DatabaseConnStr, username, password);
            Statement stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
        } catch (SQLException ex) {
            System.err.println("执行查询有错误:" + ex.getMessage());
            System.out.print("执行查询有错误:" + ex.getMessage()); // 输出到客户端
        }
        return rs;
    }
    public int update_database(String sql) { // 更新或插入数据库
        int num = 0;
        try {
            conn = DriverManager.getConnection(DatabaseConnStr, username, password);
            Statement stmt = conn.createStatement();
            num = stmt.executeUpdate(sql);
        } catch (SQLException ex) {
            System.err.println("执行插入有错误:" + ex.getMessage());
            System.out.print("执行插入有错误:" + ex.getMessage()); // 输出到客户端
        }
        CloseDataBase();
        return num;
    }
    public void CloseDataBase() { // 关闭数据库
        try {
            conn.close();
        } catch (Exception end) {
            System.err.println("执行关闭Connection对象有错误 " + end.getMessage());
            System.out.print("执行执行关闭Connection对象有错误 有错误:" + end.getMessage()); // 输出到客户端
        }
    }
}
class people {
    private String uid;
    private String name;
    private String banji;
    private int score;
    public people() {
    }
    public people(String uid, String name, String banji) {
        this.uid = uid;
        this.name = name;
        this.banji = banji;
    }
    public people(String uid, String name, String banji, int score) {
        this.uid = uid;
        this.name = name;
        this.banji = banji;
        this.score = score;
    }
    public String getUid() {
        return uid;
    }
    public void setUid(String uid) {
        this.uid = uid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBanji() {
        return banji;
    }
    public void setBanji(String banji) {
        this.banji = banji;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
}
public class manage {
    private people[] people_array; // 对象数组
    public void add_people(String uid, String name) {
        String sql = "insert into people (uid, name) values ( '" + uid + "', '" + name + "' )"; // sql插入语句
        database_manage db_obj = new database_manage();
        db_obj.update_database(sql);
    }
    public void update_people(String uid, String name) {
        String sql = "update people set name= '" + name + "' where uid= '" + uid + "'";
        database_manage db_obj = new database_manage();
        db_obj.update_database(sql);
    }
    public void delete_people(String uid) {
        String sql = "delete from people where uid= '" + uid + "'";
        database_manage db_obj = new database_manage();
        db_obj.update_database(sql);
    }
    public people query_people(String uid) {
        database_manage db_obj = new database_manage();
        String uid_new = null, name = null, banji = null;
        String sql_query = "select * from people where uid= '" + uid + "'";
        try {
            ResultSet rs = db_obj.query(sql_query);
            if (rs.next()) {
                uid_new = rs.getString("uid");
                name = rs.getString("name");
                banji = rs.getString("banji");
            }
        } catch (Exception e) {
            e.getMessage();
        }
        people new_people = new people(uid_new, name, banji);
        return new_people;
    }
    public people[] query_people_byscore(int score) {
        database_manage db_obj = new database_manage();
        String uid_new = null, name = null, banji = null;
        int score_new = 0;
        String sql_query = "select * from people where score=" + score; // sql查询语句
        try {
            ResultSet rs = db_obj.query(sql_query); // 查询后 返回结果集
            int num = 0;
            ResultSet rs_new = rs;
            while (rs_new.next()) { // 统计结果集中学生个数
                num++;
            }
            people_array = new people[num];
            int i = 0;
            rs.beforeFirst(); // 返回结果集的开始
            while (rs.next()) {
                uid_new = rs.getString("uid");
                name = rs.getString("name");
                banji = rs.getString("banji");
                score_new = rs.getInt("score");
                people_array[i] = new people(uid_new, name, banji, score_new);
                i++;
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return people_array;
    }
    public static void main(String args[]) {
        manage mr = new manage();
        people[] people_array; // 声明对象数组
        people_array = mr.query_people_byscore(100); // 返回成绩为一百的学生类数组 后输出
        int num = 0;
        num = people_array.length;
        for (int i = 0; i < num; i++) {
            System.out.println(people_array[i].getUid() + " "
                    + people_array[i].getName() + "  "
                    + people_array[i].getBanji() + "  "
                    + people_array[i].getScore());
        }
    }
}

lishixinzhi/Article/program/Java/JSP/201311/20030

java 查询数据库怎么循环输出?

连接数据库查询可以得到一个ResultSet。 然后通过:

List list = new ArrayList();
while (rs.next()) {
    创建一个实体对象po
    po.setAttribute1(rs.getString("value1"));
    po.setAttribute2(rs.getString("value2"));
    po.setAttribute3(rs.getString("value3"));
    list.add(po);
}
request.setAttribute("list", list);

返回一个list集合到界面通过:

<c:forEach items="${list}" var="c">
    <tr>
        <td>${c.value1}</td>
        <td>${c.value2}</td>
        <td>${c.value3}</td>
    </tr>
</c:forEach>

就可以了。

Java怎么查询出数据库当前月份的数据并返回给前端

你是想做到JSP页面不加入<% %>这种小脚本吧? 那可以采用EL表达式,或者一些框架的输出方式,通常用EL就可以了,因为EL就是用来运算和表达的。后台获取数据以后,这个数据可以是一个简单类型,也可以是一个对象,如果是同一个请求下的,也就是request对象没有变,那么可以用这个存储,否则要用session存储,存储数据的对象是JSP内置的对象,有page、request、session、application等,每个对象都能存储数据,但是作用域不同,page针对当前页面,request针对一个请求,session针对一个会话,application针对整个应用程序。通常session就可以了。 比如后台获取一个String的name值,那么你可以:

session.setAttribute("name", name);

那么JSP直接可以EL这样写:

${sessionScope.name}

获取这个值,这里的name是后台封装的键的名,不是后面变量name的名。

java中怎么把数据库中数据查询出来

刚刚漏了帐号密码了,现在补上:

try {
    // 这里的是MYSQL 举例
    // 加载驱动
    Class.forName("com.mysql.jdbc.Driver");
    // 创建数据库连接
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
    // 创建查询 “请求”
    PreparedStatement ps = con.prepareStatement("select * from user");
    // 返回查询结果
    ResultSet rs = ps.executeQuery();
    // 遍历结果
    while (rs.next()) {
        // 假如 User 表中有个 name 列
        System.out.println("name " + rs.getString("name"));
    }
    // 关闭
    rs.close();
    ps.close();
    con.close();
} catch (Exception e) {
    e.printStackTrace();
}

如何用Java实现数据库查询

import java.sql.*;
public class MSSQLText {
    public static void main(String args[]) {
        String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind";
        String user = "sa"; // 这里替换成你自已的数据库用户名
        String password = "sa"; // 这里替换成你自已的数据库用户密码
        String sqlStr = "select CustomerID, CompanyName, ContactName from Customers";
        try {
            // 这里的异常处理语句是必需的.否则不能通过编译!
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            System.out.println("类实例化成功!");
            Connection con = DriverManager.getConnection(url, user, password);
            System.out.println("创建连接对象成功!");
            Statement st = con.createStatement();
            System.out.println("创建Statement成功!");
            ResultSet rs = st.executeQuery(sqlStr);
            System.out.println("操作数据表成功!");
            System.out.println("----------------!");
            while (rs.next()) {
                System.out.print(rs.getString("CustomerID") + " ");
                System.out.print(rs.getString("CompanyName") + " ");
                System.out.println(rs.getString("ContactName"));
            }
            rs.close();
            st.close();
            con.close();
        } catch (Exception err) {
            err.printStackTrace(System.out);
        }
    }
}