编写java程序实现把MySQL数据库中的student表中数据进行打印输出?
1个回答
展开全部
首先导入 mysql-connector-java-5.1.45-bin.jar 包7a686964616f31333365633936
代码如下:
import java.io.*;import java.sql.*; public class App { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); // 数据库用户 String user = "root"; // 数据库密码 String password = ""; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_sale", user, password); Statement stmt = conn.createStatement(); // 查询 , 从数据库 db_sale 的 product 表中查询 id, name, qty 字段 ResultSet rs = stmt.executeQuery("SELECT id, name, qty FROM product"); // 创建输出文件 result.txt File file = new File("d://result.txt"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); while (rs.next()) { writer.write(String.valueOf(rs.getLong(1)) + "\t"); writer.write(rs.getString(2) + "\t"); writer.write(String.valueOf(rs.getInt(3))); writer.write("\r\n"); //System.out.println(rs.getLong(1)); //System.out.println(rs.getString(2)); //System.out.println(rs.getLong(3)); } writer.flush(); writer.close(); rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }}
代码如下:
import java.io.*;import java.sql.*; public class App { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); // 数据库用户 String user = "root"; // 数据库密码 String password = ""; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_sale", user, password); Statement stmt = conn.createStatement(); // 查询 , 从数据库 db_sale 的 product 表中查询 id, name, qty 字段 ResultSet rs = stmt.executeQuery("SELECT id, name, qty FROM product"); // 创建输出文件 result.txt File file = new File("d://result.txt"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); while (rs.next()) { writer.write(String.valueOf(rs.getLong(1)) + "\t"); writer.write(rs.getString(2) + "\t"); writer.write(String.valueOf(rs.getInt(3))); writer.write("\r\n"); //System.out.println(rs.getLong(1)); //System.out.println(rs.getString(2)); //System.out.println(rs.getLong(3)); } writer.flush(); writer.close(); rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询