1.思路:在原有的基础上,添加连接数据库类 Main,再添加动作类Action,初步有插入方法add,将字符串类型的问题,答案存到数据库questionTable表中。
2.源代码:
(1)连接数据库 Main
package tianaoweb.com; import java.sql.*; public class Main { public static Connection getConn(){ String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; Connection dbConn = null; String dbURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=哈哈"; String userName="sa"; String userPwd="123456"; try { Class.forName(driverName); System.out.println("加载驱动成功!"); }catch(Exception e){ e.printStackTrace(); System.out.println("加载驱动失败!"); } try{ dbConn=DriverManager.getConnection(dbURL,userName,userPwd); System.out.println("连接数据库成功!"); }catch(Exception e) { e.printStackTrace(); System.out.print("SQL Server连接失败!"); } return dbConn; } }
(2)插入数据库表数据 Action
package tianaoweb.com; import java.sql.*; public class Action { public void add(int num,String str1,String str2) throws SQLException{ Connection conn = Main.getConn(); //获取数据库连接 Statement st = conn.createStatement(); String sql = "insert into calTable([number],[question],[answer]) values('"+ num +"','" + str1 + "','" + str2 + "')"; st.executeUpdate(sql); st.close(); conn.close(); } }
3.截图: