今天进行了软件构造的作业题书写。
package com.example.test; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JDBC { private static Connection connection; private static String url="jdbc:mysql://localhost:3306/?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; private static String user="root"; private static String pass=""; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); }catch(ClassNotFoundException e){ e.printStackTrace(); } } public static Connection getConnection() { try { connection=DriverManager.getConnection(url,user,pass); }catch(SQLException e) { e.printStackTrace(); } return connection; } public static List<Question> find(int num) {//查询 Connection conn=JDBC.getConnection(); PreparedStatement pre=null; ResultSet res=null; List<Question> questionList=new ArrayList<>(); String str=null; String sql="SELECT * FROM questions limit "+num; try { pre=conn.prepareStatement(sql); res=pre.executeQuery(); while(res.next()) { String name=res.getString ("ques"); int pass=res.getInt("res"); Question question=new Question(name,pass); questionList.add(question); } } catch(SQLException e) { e.printStackTrace(); System.out.println("查询错误"); }finally{ JDBC.release(conn, pre, res); } return questionList; } public static void add(List<Calculate> questionList) {//添加 Connection connn=JDBC.getConnection(); try { for(int i=0;i<questionList.size();i++) { Calculate calculate=questionList.get(i); String sql="insert into questions (ques,res) values (?,?) "; PreparedStatement ps = connn.prepareStatement(sql); ps.setString(1, calculate.toString()); ps.setInt(2, calculate.getResult()); ps.executeUpdate(); } } catch(SQLException e) { e.printStackTrace(); System.out.println("insert错误"); }finally{ JDBC.release(connn, null, null); } } public static void release(Connection connection,Statement statement,ResultSet resultSet) { try { if(connection!=null) { connection.close(); } if(statement!=null) { statement.close(); } if(resultSet!=null) { resultSet.close(); } } catch(SQLException e) { e.printStackTrace(); } } }
之后进行数据库的读出写入。
点击两次读出MySQL
标签:总结,questionList,String,res,每日,try,static,pass From: https://www.cnblogs.com/syhxx/p/17852763.html